【问题标题】:How do I dynamically name a model of a directive scope with 2 way binding?如何使用 2 路绑定动态命名指令范围的模型?
【发布时间】:2014-06-17 18:48:33
【问题描述】:

我正在尝试使用ng-repeat 将对象值动态传递给指令,如下所示:

<td ng-repeat="attr in demographicAttrs">
  <yes-no name="{{ attr }}-{{ $index }}"
    model="ambassador.demographic.{{ attr }}"
    update="calcScore(ambassador)"></yes-no>
</td>

指令定义为

function (
  $rootScope
) {
  "use strict";

  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'templates/yesNo.html',
    scope: {
      "name": "@",
      "model": "=",
      "update": "&"
    },
    link: function(scope, element, attrs) {
      scope.$watch('model', function(value) {
        scope.update();
      });
    }
  };
};

所以我试图动态生成要在ambassador.demographic.{{ attr }} 中观看的模型,但是= 指令的2 路绑定不喜欢以这种方式生成的值。

我收到此错误:https://docs.angularjs.org/error/$parse/syntax?p0=%7B&p1=is%20an%20unexpected%20token&p2=24&p3=ambassador.demographic.%7B%7B%20attr%20%7D%7D&p4=%7B %7B%20attr%20%7D%7D

我该怎么做?

更新

【问题讨论】:

  • 如何从概念上改变它并在指令中移动重复(并且只是传递整个模型对象)?这对您的用例有用吗?

标签: angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

更改模型表达式以使用 javascript 括号表示法:

model='ambassador.demographic[attr]'

Fiddle

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多