javascript - Angular ng-model绑定(bind)到元素名称

标签 javascript angularjs

是否有一种语法允许我使用 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/

相关文章:

angularjs - JS Promises - 使这个 promise 嵌套更有效的方法?

javascript - ng-repeat 的问题

angularjs - Angular.js createElement 没有创建元素

javascript - 如何更改根组件中的数据?

javascript - 将元素的 ID 传递给 jquery 函数

javascript - 如何在 QML 中使用forwardTo 在 TextInput 上显示光标

angularjs - 如何将 ng-model 字符串格式化为 Angular Material 日期选择器的日期

service - 为什么在 Angular 中使用服务?

javascript - Ember.js - Ember 数据不返回模型

javascript - 服务中的只读属性