是否有一种语法允许我使用 ng-model 绑定(bind)到与我要绑定(bind)到的元素同名的范围属性?
所以,在下面的例子中:
<input name="myinputname" type="text" ng-model="?" />
有什么我可以用作 ng-model 值的东西,它将解析为“myinputname”,而不需要我对其进行硬编码吗?
最佳答案
如果你能从服务器端添加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
关于javascript - Angular ng-model绑定(bind)到元素名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793197/