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