jwize
jwize

Reputation: 4165

How do I pass any array from ng-repeat to AngularJs attribute directive?

I have a list of hierarchy of menu items where each item has a child list. For The menuItems property is from the controller scope(list of parents). I want to pass an array to be consumed by the directive on both levels of the following example.

Html Code

<div sortable="menuItems">
    <div ng-repeat="item in menuItems">
        ...
        <div sortable="item.Children">
            <div ng-repeat="child in menuItems.Children">...</div>
        </div>
    </div>
</div>

Directive code

app.directive('sortable', function ($timeout) {
    return {
        restrict: 'A',
        link: function($scope, $elem, attrs) {
         // I need access by the array in here.
        }
    };
});

I have set the sortable attribute to the value of the name of the list which obviously is not working for me.

Upvotes: 0

Views: 260

Answers (2)

jwize
jwize

Reputation: 4165

The problem was the isolate-scope for the directive was not set.

app.directive('sortable', function ($timeout) {
    return {
        restrict: 'A',
        link: function ($scope, $elem, attrs) {...},
        scope: { items: '=' }
    }

   <div id="sortable-basic" sortable items="menuItems">

Upvotes: 0

GregL
GregL

Reputation: 38121

You can set up a scope watch (or collection watch), since the value of the attribute is the scope expression.

app.directive('sortable', function ($timeout) {
    return {
        restrict: 'A',
        link: function($scope, $elem, attrs) {
             $scope.$watchCollection(attrs.sortable, function (newCollection, oldCollection) {
                 // (do something with newCollection)
             });
        }
    };
});

Upvotes: 1

Related Questions