Why are my AngularJS directives sharing scope?

后端 未结 4 453
不知归路
不知归路 2020-12-15 21:29

I\'ve tried to make a simple directive which displays a name and allows it to be change. When I put multiple directive on the name page they all seem to share the name attri

相关标签:
4条回答
  • 2020-12-15 21:37

    By default if you don't isolate the scope of a directive you will share the "outside" scope with all instances of your person directive. With your current implementation you'd need to create a different controller each time in order to re-use such a directive.

    BUT there is a solution to this flaw and it s called isolate scope. To do this, you can use a directive's scope option like so :

    return {
      restrict: 'E',
      replace: true,
      scope : {}, // this is where the magic happens
      template: "<span>Current name = {{name}}<a href='' class='btn' ng-click='setName()'>Change name</a><br></span>",
      link : link,
    }
    

    You have a complete example and explenation over here section Isolating the Scope of a Directive

    0 讨论(0)
  • 2020-12-15 21:42

    You have 3 options for scope in AngularJS directives

    1. false (Uses parent scope)
    2. true (creates own scope and also inherits from parent, i.e you can access items defined in parent scope as well)
    3. {} (creates an isolated scope)

    Let me demonstrate this using $rootScope

        app.run(function($rootScope){
          $rootScope.firstname = "Root scope name";
          $rootScope.rootValue = "Root value";
        });
    
        app.directive("sampleDirective",function(){
          return{
            template:"<div>{{firstname}}{{rootValue}}</div>",
     // here rootValue will be accessible as its inherited from parent. You can overwrite this as well
            scope : true,
            controller:['$scope',sampleDirectiveScope]
          };
        });
    
        function sampleDirectiveScope($scope){
          $scope.firstname = "child scope changing name - ";
        };
    
        app.directive("isolatedScopeDirective",function(){
          return {
            controller:isolatedFunction,
            template:" this has isolated scope ,<div>{{rootValue}}</div>", 
        // here rootValue will not be accessible because it is isolated and not inheriting from parent
            scope: {}
          };
        });
    
        function isolatedFunction($scope){ 
          //define values for this scope
        };
    

    Check this live demo

    0 讨论(0)
  • 2020-12-15 21:53

    As mentioned in previous answers, the default behavior of AngularJS directives is to share the scope that they are included in. This behavior is changed via the scope parameter in the directive definition object.

    You can view the documentation for the scope argument in this section of the AngularJS documents: http://docs.angularjs.org/api/ng.$compile#description_comprehensive-directive-api_directive-definition-object

    This argument has three options:

    1. scope: false - the default behavior of sharing the scope the directive is included in

    2. scope: true - create a new scope for the directive that acts like other child scopes and prototypically inherits from its parent scope

      • See Example 1
    3. scope: {} - create an isolated scope that does not prototypically inherit from its parent scope

      • See Example 2

    As you can see with the JSBin examples, both options 2 and 3 will work for your example. The difference is whether you want your new scopes isolated or not.

    The directives section of the AngularJS guide has a good section on why isolated scope can help create better reusable modules with directives: AngularJS Guide: Isolating the Scope of a Directive

    0 讨论(0)
  • 2020-12-15 21:55

    By default, directives share the same scope. But if needed, you can use isolated scope for your directives: use scope: {} as field in your directive definition.

    app.directive('person', function () {
    
        function link ($scope, elem, attrs, ctrl) {     
    
            $scope.name = "OLD"        
    
            $scope.setName = function() {
                $scope.name = 'NEW';
            }
        }
    
        return {
          restrict: 'E',
          scope: {}
          replace: true,
          template: "<span>Current name = {{name}}<a href='' class='btn' ng-click='setName()'>Change name</a><br></span>",
          link : link,
        }
    
      });
    
    0 讨论(0)
提交回复
热议问题