huan feng
huan feng

Reputation: 8623

Multiple same directive share the scope variable?

Does controller share it's scope if I use the directive in one page multiple times? Although I think is not shared, I still want someone to help me understand this point.

If I define the variable 'isWidgetEnabled' in fooController, will it share in both two directives, if I want each directive 'foo' has its own variable, how can I do it?

js:

angular.module("module")
  .controller("fooController", ["$scope", function($scope) {
    ...
  })
  .directive("foo", function() {
    return {
      restrict: "E",
      controller: "fooController",
      link: function($scope, $element, $attrs) {
        // Do some things with the scope of the controller here
      }
    }
  });

html:

<html>
    <head>
    <!-- Scripts here -->
    </head>
    <body ng-app="module">
        <foo/>
        <foo/>
    </body>
</html>

Upvotes: 0

Views: 3669

Answers (2)

Charlie
Charlie

Reputation: 23798

If you need to maintain a separate variable in the controller for each directive, you should pass these variables explicitly through the directive attributes and bind them to the isolated scope via Prefixes.

Here is an example. I have the foo directive in this code and the directive is used in two places in the dom. The directive modifies a scope variable depending on an attribute of the dom element it is caled.

The code is set to set the html of the <span> elements with the html of the directive elements.

<div ng-controller="fooController">       

   <div foo scopevar="dir1Data">Div1</div>   <!--Here you tell which controller variable to effect by the directive-->
   <div foo scopevar="dir2Data">Div2</div>

   <span>{{dir1Data}}</span><br>
   <span>{{dir2Data}}</span>         

</div>

And your angular code

.controller('fooController', function($scope) { 

    $scope.dir1Data = '';
    $scope.dir2Data = '';                       
})

.directive('foo', function(){
    return {

        scope: {

            //You set the prefix "=" here. This tells angular the variable name 
            //mentioned in the scopevar attribute should be two-way bound
            //to the controller scope 

            scopevar:'='  
        },

        link: function(scope, ele, attr) {
            scope.scopevar = ele.html();   //Here I modify the controller variable
        }
    }                
})

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

Yes, it will be shared in all the directives, because the scope of your directive is inherited by default, which means that it shares the same scope as the controller.

Upvotes: 1

Related Questions