多个相同的指令共享范围变量



如果我在一个页面中多次使用该指令,控制器是否共享其作用域?虽然我认为没有分享,但我还是希望有人帮助我理解这一点。

如果我在 fooController 中定义变量 'isWidgetEnabled',它会在两个指令中共享吗,如果我希望每个指令 'foo' 都有自己的变量,我该怎么做?

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

是的,它将在所有指令中共享,因为默认情况下会继承指令的作用域,这意味着它与控制器共享相同的作用域。

如果需要在控制器中为每个指令维护一个单独的变量,则应通过指令属性显式传递这些变量,并通过前缀将它们绑定到隔离的作用域。

下面是一个示例。我在这个代码中有 foo 指令,该指令在 dom 中的两个地方使用。该指令根据它所计算的 dom 元素的属性修改范围变量。

该代码设置为使用指令元素的 html 设置<span>元素的 html。

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

和你的角度代码

.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
        }
    }                
})

最新更新