Angularjs - $ rootScope在指令链接功能 [英] Angularjs - $rootScope in directive link function
问题描述
我问这个问题,因为我不是怎么想rootscope的传递给指令的依赖相当清楚
I am asking this question because I am not quite clear on how to think of rootscope as a dependency passed to directives
我有需要显示从$ rootScope ...
I have a directive that needs to display some information from $rootScope ...
我认为我需要到$ rootScope传递给一个指令,但是当我写一个指令,这样它似乎工作。
I thought I needed to pass the $rootScope to a directive but when I write a directive like this it seems to work.
.directive("myBar", function () {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
我什么时候需要做到这一点?
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
我和我如何使用rootScope如果我需要它的指令的链接功能 - ?或者我应该这样做的指令的控制器
Can I and HOW do I use rootScope if I need it in the link function of the directive - or should I do it in the controller of the directive?
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
transclude: true,
replace: true,
link: function (scope, element, attrs, rootScope) {
rootScope.rsUser = { firstName: 'Joe' };
rootScope.rsUser = { welcome: 'Welcome' };
},
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
我rootScope数据在运行函数中定义的
My rootScope data is defined in run function
.run(function ($rootScope) {
$rootScope.rsLabels = {
welcome: 'Welcome'
};
$rootScope.rsUser = {
firstName: 'Joe'
};
});
感谢您!
推荐答案
从我的实验\\经验,似乎因为所有$范围最终从$ rootScope继承,你将能够访问Internet上的数据而不必要求它作为一个服务,以下标准的JavaScript原型继承规则。如果你要设置你的指令错误或{}你会发现,你不能再访问它。
From my experiments \ experience, it seems that since all $scopes ultimately inherit from the $rootScope you will be able to access data on it without requesting it as a service, following standard javascript prototypical inheritance rules. If you were to set the scope property in your directive to false or {} you will find that you can no longer access it.
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
scope: { // Isolate scope, no $rootScope access anymore) }
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
例如: http://jsbin.com/bequy/1/edit
这篇关于Angularjs - $ rootScope在指令链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!