Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular multiple instances of same directive, scope is not isolated

I have a problem when creating multiple directives with isolated scope: when I change something in 1st directive it also makes changes in all other directives.

Here is a working example: http://plnkr.co/edit/drBghqHHx2qz20fT91mi?p=preview (try to add more of Type1 'Available notifications' - a change in 1st will reflect in all other directives of Type1)

I found some solutions to similar problems here but they don't work in my case. Also found a working solution with mapping 'subscription' data to local scope variables in directive (app.js, line 76) but I think there should be a more general way to do this right?

like image 632
marebine Avatar asked Feb 14 '23 10:02

marebine


1 Answers

In your directive 'notificationitem' you have the following code, keep it in mind as i explan:

// if all variables are mapped in this way than works
//$scope.enabled = $scope.subscription.enabled;

The reason why all of the 'isolated' scopes are updating is because of this code in your scope declaration in the same directive (notificationitem):

scope: {
      subscription: '=',
      index: '@'
    },

The equal sign on subscription is angular's way of saying "Whenever the current scope updates, go to the parent and update that value as well." This means whenever you update your 'isolated' scope, it updates the parent scope as well. Since all of these isolated scopes are binding to the parent, they will change as well.

Since you want the subscription.value to be the default value of that text field, you will need to do exactly what your commented code is doing:

scope.value = scope.subscription.value;

This will create an isolated value inside of the isolated scope. When scope.value changes, scope.subscription.value will not. All of the text fields now have their own 'value' to keep track of.

Check out this article for information on directive bindings: http://www.ng-newsletter.com/posts/directives.html

Also, another way to get the default value would be to inject your service into the directive, if you don't like the above solution. Hope this all helps.

like image 198
Vinny Avatar answered Feb 17 '23 02:02

Vinny