0

我想爲佔位符創建自定義角度指令。設置角度指令內元素的值

的指令代碼如下:

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"> 

我正在使用angularScript和打字稿。

但在上面的示例中,當第一個視圖加載時,它將value屬性設置爲我們傳遞的佔位符。但在第一次焦點丟失後,突然開始工作。

我不知道爲什麼價值(「XXX-XX-XXXX」)第一次沒有出現。

如果可能,請提前致謝。

回答

1

instanceElement.on是一個jQuery命令 - >在它結束的回調運行$範圍。$適用()提醒角度變化的模型

你應該也可以用你的NG-模式「$ scope.myVal「,而不是instanceElement.val()來爲你的輸入分配值

+0

你好koolunix感謝我應用到我的應用程序的偉大解決方案,它的工作。 –

+0

@kookunix,我確實在焦點處理程序中檢查了它,並且它開始了,但是如果我會在鏈接函數內執行相同的操作,它將拋出錯誤$摘要已在進行中。 –

+0

我在鏈接函數裏面寫了這個東西,因爲我希望它第一次被設置爲「XXX-XX-XXXX」。 –