Bind AngularJS directive to array mapping

I have a directive that accepts an array of objects. When a directive is declared in the markup, the area has an array of objects that wrap those that the directive needs. Therefore, I need to apply the display function in the array. What is the right way to do this so that updates made to the source array are reflected inside the directive?

Here is a plunker with a naive approach (which I was surprised to see mostly "work", with the exception of a lot of $ digest errors): http://plnkr.co/edit/GUCZ3c

+3
source share
2 answers

Angular, , , (, ). question .

. :

app.controller('MainCtrl', function($scope) {  
    $scope.people = [
        { name: 'Alice'}, 
        { name: 'Bob' },
        { name: 'Chuck' }
    ];

    $scope.addName = function(name) {
        $scope.people.push({name: name});
    };

    $scope.$watch(function() { return $scope.people.length; }, function() {
        $scope.names = $scope.people.map(function(p) { return p.name; });
    });
});

. Plunker.

. , $watch , @KrisBraun.

+4

, , . .

app.directive('myDirective', function($compile) {
  return {
    restrict: 'E',
    scope: {
      names: '&namesFunc'
    },
    template: '<div><p>JSON: {{names() | json}}</p><p>Names:</p><ul><li ng-repeat="name in names()">{{name}}</li></ul></div>',
    replace: true,
    link: function(scope, elem, attr, ctrl) {
    }
  };
});
+1

All Articles