为什么不能在$ rootScope与分离范围指令的模板进行访问? [英] Why can't the $rootScope be accessed in the template of a directive with isolate scope?
本文介绍了为什么不能在$ rootScope与分离范围指令的模板进行访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过分离范围的指令的模板似乎不能够访问的控制(Ctrl键)$ rootScope变量其中,但是,会出现在指令的控制器。我明白为什么控制器(Ctrl键)$范围的变量是不是在隔离范围内可见。
HTML
< DIV NG-应用=应用程序>
< DIV NG控制器=CTRL>
<我的模板>< /我的模板>
< / DIV> <脚本类型=文/ NG-模板ID =我-template.html>
<标签NG点击=测试(等等)>点击< /标签>
< / SCRIPT>
< / DIV>
JavaScript的:
angular.module(应用,[])
.controller(Ctrl键,功能CTRL1($范围,$ rootScope){
$ rootScope.blah =你好;
$ scope.yah ='世界'
})
.directive('MyTemplate的',函数(){
返回{
限制:'E',
templateUrl:我-template.html',
范围: {},
控制器:[$范围,$ rootScope功能($范围,$ rootScope){
的console.log($ rootScope.blah);
的console.log($ scope.yah);, $ scope.test =功能(ARG){
的console.log(ARG);
}
}]
};
});
该变量没有分离范围访问 - 这可以通过注释分离范围线可以看出:
//范围:{},
解决方案
您可以试试这种方法使用了 $ root.blah
HTML
<标签NG点击=测试($ root.blah)>点击< /标签>.controller(Ctrl键,功能CTRL1($范围,$ rootScope){
$ rootScope.blah =你好;
$ scope.yah ='世界'
})
.directive('MyTemplate的',函数(){
返回{
限制:'E',
templateUrl:我-template.html',
范围: {},
控制器:[$范围,$ rootScope功能($范围,$ rootScope){
的console.log($ rootScope.blah);
的console.log($ scope.yah); $ scope.test =功能(ARG){
的console.log(ARG);
}
}]
};
});
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>
.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屋!
查看全文