为什么不能在具有隔离作用域的指令的模板中访问 $rootScope? [英] Why can't the $rootScope be accessed in the template of a directive with isolate scope?
问题描述
使用隔离作用域,指令的模板似乎无法访问控制器 ('Ctrl') $rootScope 变量,然而,该变量确实出现在指令的控制器中.我明白为什么控制器 ('Ctrl') $scope 变量在隔离范围内不可见.
HTML:
<div ng-controller="Ctrl"><我的模板></我的模板><script type="text/ng-template" id="my-template.html"><label ng-click="test(blah)">点击</label>
JavaScript:
angular.module('app', []).controller('Ctrl', function Ctrl1($scope, $rootScope) {$rootScope.blah = '你好';$scope.yah = '世界'}).directive('myTemplate', function() {返回 {限制:'E',templateUrl: 'my-template.html',范围: {},控制器:[$scope",$rootScope",函数($scope,$rootScope){console.log($rootScope.blah);console.log($scope.yah);,$scope.test = 函数(参数){控制台日志(参数);}}]};});
在没有隔离范围的情况下访问该变量 - 从注释隔离范围行可以看出:
//作用域:{},
您可以尝试使用 $root.blah
html
javascript
angular.module('app', []).controller('Ctrl', function Ctrl1($scope, $rootScope) {$rootScope.blah = '你好';$scope.yah = '世界'}).directive('myTemplate', function() {返回 {限制:'E',templateUrl: 'my-template.html',范围: {},控制器:[$scope",$rootScope",函数($scope,$rootScope){console.log($rootScope.blah);console.log($scope.yah);$scope.test = 函数(参数){控制台日志(参数);}}]};});
With isolate scope the template of the directive does not seem to be able to access the controller ('Ctrl') $rootScope variable which, however, does appear in the controller of the directive. I understand why the controller ('Ctrl') $scope variable isn't visible in the isolate 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);
}
}]
};
});
The variable is accessed with no isolate scope - as can be seen by commenting the isolate scope line:
// scope: {},
You can try this way out using $root.blah
html
<label ng-click="test($root.blah)">Click</label>
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);
}
}]
};
});
这篇关于为什么不能在具有隔离作用域的指令的模板中访问 $rootScope?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!