【问题标题】:Modifying the scope of an Isolated Scope Directive in Angular在 Angular 中修改独立作用域指令的作用域
【发布时间】:2016-04-06 02:18:47
【问题描述】:

我正在尝试理解指令中的独立作用域。我有以下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.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 这样的独立指令的范围内?这是fiddle

谁能解释一下这里发生了什么。谢谢!

【问题讨论】:

  • 顾名思义,隔离范围仅在指令代码和模板中可见。您不将模板与指令一起使用,而是绑定在继承父范围(或在使用 scope: true 时为子范围)的嵌套 HTML 元素上。隔离作用域被设计为与可重用组件一起使用,并试图在指令和控制器之间提供更高的安全性——例如避免范围上的名称冲突。在第三种情况下你想要的是一个自定义指令模板example here
  • 谢谢。所以在isolation-test div 中,作用域实际上是父作用域(与same-test 相同)。由于没有定义模板,因此无法访问隔离范围。谢谢,我之前不了解模板和隔离范围之间的关系。现在说得通了。

标签: javascript angularjs


【解决方案1】:

在您的 isolateTest 指令中,我将您的 scope: {} 切换为 scope: true,并且我能够启动您的函数。

更新小提琴: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 的评论澄清了孤立作用域在这里是如何真正起作用的。
猜你喜欢
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多