Angular ng-model绑定到元素名称

时间:2014-07-17 00:49:20

标签: javascript angularjs

是否有一种语法允许我使用ng-model绑定到与我绑定的元素同名的scope属性?

因此,在以下示例中:

<input name="myinputname" type="text" ng-model="?" />

我可以使用哪些东西作为ng-model值解析为“myinputname”,而不需要我对其进行硬编码?

1 个答案:

答案 0 :(得分:2)

如果您可以从服务器端添加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