【问题标题】:Setting the value of element inside the angular directive在 angular 指令中设置元素的值
【发布时间】:2014-03-05 13:43:42
【问题描述】:

我想为占位符制作自定义角度指令。

指令代码如下:

class customDirective {

restrict: string = "A";
link = (scope: ng.IScope,
    instanceElement: ng.IAugmentedJQuery,
    instanceAttributes: ng.IAttributes,
    controller: any,
    transclude: ng.ITranscludeFunction) => {
    instanceElement.val((<any>instanceAttributes).tsplaceholder);
    instanceElement.on("focus", (eventObj: JQueryEventObject) => {
        if (instanceElement.val() === (<any>instanceAttributes).tsplaceholder) {
            instanceElement.removeClass("gray-textbox");
            instanceElement.val("");
        }
    });

    instanceElement.on("blur", (eventObj: JQueryEventObject) => {
        if (instanceElement.val() === "") {
            instanceElement.addClass("gray-textbox");
            instanceElement.val((<any>instanceAttributes).tsplaceholder);
        }
    });
    instanceElement.addClass("gray-textbox");
    //instanceElement.attr("value", (<any>instanceAttributes).tsplaceholder);
    //this.$compile(instanceElement.contents())(scope);
}

}

taxSimpleApp.directive("tsplaceholder", () => {
return new customDirective();
});

我正在使用下面的 html 代码。

<input name="ssn2"
      id="jenish"
      type="text"
      required                               
      ng-model="myVal" 
      tsplaceholder="XXX-XX-XXXX">

我正在使用带有打字稿的角度。

但在上面的示例中,当第一个视图加载时,它确实将 value 属性设置为我们传递的占位符。但是在第一个焦点丢失后它突然开始工作。

我不知道为什么 value("XXX-XX-XXXX") 没有第一次出现。

如果可能的话,提前感谢您的任何帮助。

【问题讨论】:

    标签: javascript angularjs angularjs-directive typescript angular-ui


    【解决方案1】:

    instanceElement.on 是一个 jquery 命令-> 在它的回调结束时运行 $scope.$apply() 来提醒 Angular 模型的变化

    您还应该使用您的 ng-model "$scope.myVal",而不是 instanceElement.val() 来为您的输入赋值

    【讨论】:

    • 您好,koolunix 感谢我将出色的解决方案应用到我的应用程序中,并且成功了。!
    • @kookunix ,我确实在焦点处理程序中检查了这个并且它开始了,但是如果我在链接函数中做同样的事情,它就会抛出错误 $digest 已经在进行中。
    • 我在链接函数中写了这个东西,因为我希望它第一次被设置为“XXX-XX-XXXX”。
    • 对于你在做什么,我会检查“ui-mask”-> angular-ui.github.io/ui-utils/#/mask
    猜你喜欢
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    相关资源
    最近更新 更多