在Angular中修改隔离作用域指令的范围

3

我想了解指令中的隔离作用域。 我有以下HTML:

<div new-test>
  <h4>new scope : {{msg}}</h4>
  <button ng-click="clicker()">new test</button>
  <hr>
</div>
<div same-test>
  <h4>same as parent scope : {{msg}}</h4>
  <button ng-click="clicker()">same test</button>
  <hr>
</div>
<div isolate-test>
  <h4>isolated scope : {{msg}}</h4>
  <button ng-click="clicker()">isolated test</button>
  <button ng-click="ftn()">own ftn</button>
  <hr>
</div>

以下是 Angular 指令:

angular.module('myApp', []);

angular.module('myApp')

.directive('newTest', [function() {
    return {
    scope: true,
    link: function(scope, elem, attr) {
        scope.msg = 'new scope';
        scope.clicker = function() {
          console.log("New Scope");
        };
    }
  }
}])

.directive('sameTest', [function() {
    return {
    scope: false,
    link: function(scope, elem, attr) {
        scope.msg = 'same scope';
        scope.clicker = function() {
          console.log("Same Scope");
        };
    }
  }
}])

.directive('isolateTest', [function() {
    return {
    restrict: 'A',
    scope: {},
    link: function(scope, elem, attr) {
        scope.msg = 'isolated scope'; // this doesn't exist
        scope.clicker = function() {
          console.log("Isolated Scope"); // this is never called
        };
        scope.ftn = function() {
          console.log("own ftn"); // or this
        };
    }
  }
}]);

我认为已经添加到isolateTest指令范围内的函数或变量都不存在。如果我点击isolate test按钮,那么将调用same-test指令中的clicker函数。这是怎么回事?我认为该按钮以及在div元素之间的任何其他元素都存在于一个隔离范围内?如何向像isolateTest这样的隔离指令的作用域中添加“本地”功能?这是示例

有人可以解释一下这里发生了什么吗?谢谢!


2
正如其名称所示,隔离作用域仅在指令代码和模板中可见。您不使用模板来处理指令,而是绑定嵌套的HTML元素,这些元素继承父作用域(或在使用scope:true时继承子作用域)。隔离作用域旨在与可重用组件一起使用,并尝试在指令和控制器之间提供更多安全性 - 例如,避免作用域上的名称冲突。在第三种情况下,您需要一个自定义指令模板示例在此处 - csharpfolk
谢谢。所以在 isolation-test div 中,作用域实际上是父级作用域(与 same-test 相同)。由于没有定义模板,因此无法访问隔离作用域。谢谢,我之前不理解模板和隔离作用域之间的关系。现在有了更清晰的认识。 - CSharp
1个回答

1
在您的isolateTest指令中,我将您的scope: {}更改为scope: true,这样我就能够使您的函数触发。
更新后的fiddle:https://jsfiddle.net/rjcmjd0k/11/
.directive('isolateTest', [function() {
    return {
    restrict: 'A',
    scope: true,
    link: function(scope, elem, attr) {
        scope.msg = 'isolated scope';
        scope.clicker = function() {
       console.log("Isolated Scope");
      };
      scope.ftn = function() {
        console.log("own ftn");
      };
    }
  }
}]);

谢谢,但我已经知道将作用域更改为“true”会这样做。csharpfolk的评论澄清了隔离范围在这里的真正工作方式。 - CSharp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接