使用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);
}
}]
};
});
该变量是在没有隔离范围的情况下访问的-可以通过注释隔离范围行来查看:
// scope: {},
发布于 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属性访问根作用域的属性。
https://stackoverflow.com/questions/23595866
复制相似问题