我问这个问题是因为我不太清楚如何将 rootscope 作为传递给指令的依赖项
我有一个指令需要显示 $rootScope 中的一些信息...
我认为我需要将 $rootScope 传递给指令,但是当我编写这样的指令时,它似乎可以工作。
.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,我可以以及如何使用 rootScope - 或者我应该在指令的 Controller 中使用 rootScope?
.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 数据在 run 函数中定义
.run(function ($rootScope) {
$rootScope.rsLabels = {
welcome: 'Welcome'
};
$rootScope.rsUser = {
firstName: 'Joe'
};
});
谢谢!
最佳答案
你可以这样做:
{{$root.rsLabels.welcome}}
关于Angularjs - 指令链接函数中的 $rootScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21736824/