首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么不能在isolate作用域的指令模板中访问$rootScope?

为什么不能在isolate作用域的指令模板中访问$rootScope?
EN

Stack Overflow用户
提问于 2014-05-12 01:41:00
回答 1查看 90.6K关注 0票数 82

使用isolate作用域,指令的模板似乎无法访问控制器('Ctrl') $rootScope变量,但是,该变量确实出现在指令的控制器中。我理解为什么控制器('Ctrl') $scope变量在隔离作用域中不可见。

HTML:

<div ng-app="app">
    <div ng-controller="Ctrl">
        <my-template></my-template>
    </div>

    <script type="text/ng-template" id="my-template.html">
        <label ng-click="test(blah)">Click</label>
    </script>
</div>

JavaScript:

angular.module('app', [])
    .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
        $rootScope.blah = 'Hello';
        $scope.yah = 'World'
    })
    .directive('myTemplate', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-template.html',
            scope: {},
            controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                console.log($rootScope.blah);
                console.log($scope.yah);,

                $scope.test = function(arg) {
                    console.log(arg);
                }
            }]
        };
    });

JSFiddle

该变量是在没有隔离范围的情况下访问的-可以通过注释隔离范围行来查看:

        // scope: {},
EN

回答 1

Stack Overflow用户

发布于 2019-09-25 20:42:06

我知道这是一个古老的问题。但是它不能满足我的疑问,即为什么隔离作用域不能访问$rootscope中的属性。

所以我在角库里找到了-

$new: function(isolate) {
  var ChildScope,
      child;

  if (isolate) {
    child = new Scope();
    child.$root = this.$root;
    child.$$asyncQueue = this.$$asyncQueue;
    child.$$postDigestQueue = this.$$postDigestQueue;
  } else {

    if (!this.$$childScopeClass) {
      this.$$childScopeClass = function() {
        // blah blah...
      };
      this.$$childScopeClass.prototype = this;
    }
    child = new this.$$childScopeClass();
  }

这是angular在创建新作用域时调用的函数。很明显,任何隔离的作用域都不是典型地继承根作用域。相反,只有根作用域被添加为新作用域中的属性“$root”。因此,我们只能从新隔离作用域中的$root属性访问根作用域的属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23595866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档