1
是否有一種語法允許我使用ng-model綁定到與綁定到的元素具有相同名稱的scope屬性?Angular ng-model綁定到元素名稱
那麼,在下面的例子:
<input name="myinputname" type="text" ng-model="?" />
是有什麼我可以爲將解析「myinputname」的NG-模型值使用,而不需要我進行硬編碼呢?
是否有一種語法允許我使用ng-model綁定到與綁定到的元素具有相同名稱的scope屬性?Angular ng-model綁定到元素名稱
那麼,在下面的例子:
<input name="myinputname" type="text" ng-model="?" />
是有什麼我可以爲將解析「myinputname」的NG-模型值使用,而不需要我進行硬編碼呢?
如果您可以從服務器端添加ng-model
,它將會有更好的性能。
,但如果你真的想這樣做的客戶端,你可以寫一個自定義的指令,在編譯時將自動添加ng-model
這樣的:
app.directive('myModel', function($compile) {
return {
restrict: 'A',
replace: false,
priority: 1000,
terminal: true, // these terminal and a high priority will stop all other directive from being compiled at first run
link: function (scope, element, attrs) {
attrs.$set('ngModel', attrs.name); // set value of ng-model to be the same as the name attribute
attrs.$set('myModel', null); // remove itself to avoid a recusion
$compile(element)(scope); // begin compiling other directives
}
};
});
,並使用它像這樣:
<input type="text" name="myinputname" my-model />
第一次編譯後它會自動變成:
<input type="text" name="myinputname" ng-model="myinputname" />
Plunker例如:http://plnkr.co/edit/hBQQMDTr6cYtHzFvoAaQ?p=preview
可以作出這樣的處理的東西你自己smartInput指令: –
Mik378
沒有簡單的語法,如果你有很多元素可以爲他們創造一個指令,讓你分享屬性。應該注意,儘管...非常強烈建議確保你在'ng-model'中有一個**點**,所以它不是一個原始的對象引用 – charlietfl
我想將ng-model屬性添加到一個輸入呈現由服務器端代碼(ASP.NET MVC準確地說)。理想情況下,我會添加ng-model屬性,它將默認爲由服務器代碼生成的字段名稱。 – Wayne