0

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.

2 Answers 2

1

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)
             });
        }
    };
});
Sign up to request clarification or add additional context in comments.

4 Comments

says attrs is not defined so I must be doing something wrong here
Is attrs the exact name of the 3rd parameter to the link function? Or are you calling it $attrs in the function params and then trying to refer to attrs in the function body?
attrs.sortable is a string, not a collection, so until I get the array I haven't solved my issue. I need the array from the directive attribute sortable="menuItems" somehow to be available in my link function.
@jwize Yes, that is exactly what you get inside the watch listener function - newCollection will be that array. By watching the attrs.sortable string, AngularJS will evaluate that expression and invoke the listener once initially and then afterwards for any changes.
0

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">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.