0

I'm trying to use a ng-repeat to dynamically pass in an object value to a directive, like so:

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

where the directive is defined as

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();
      });
    }
  };
};

So I'm trying to dynamically generate the model to be watched in ambassador.demographic.{{ attr }}, but the = 2 way binding for directives, doesn't like the value being generated that way.

I get this error: 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

How would I do this?

Updates

Community
  • 1
  • 1
zlog
  • 3,316
  • 4
  • 42
  • 82
  • what about changing it conceptually and move the repeat inside the directive (and just passing the whole model object)? would that work for your use case? – Sebastian May 01 '14 at 09:48

1 Answers1

1

Change the model expression to use the javascript bracket notation:

model='ambassador.demographic[attr]'

Fiddle

Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
  • That works! But mine looked more like this: http://jsfiddle.net/Zgm5X/2/ (which errors when you click on the radio buttons). Needed to also initialise the `demographic` key, as per: http://jsfiddle.net/Zgm5X/3/ – zlog May 01 '14 at 11:05