GRo*_*ing 47 angularjs angularjs-directive angularjs-scope rootscope
我问这个问题是因为我不太清楚如何将rootcope视为传递给指令的依赖
我有一个指令,需要显示来自$ rootScope的一些信息......
我以为我需要将$ rootScope传递给一个指令但是当我写这样的指令时它似乎有效.
.directive("myBar", function () {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
Run Code Online (Sandbox Code Playgroud)
我什么时候需要这样做?
.directive("myBar", function ($rootScope) {
return {
restrict: "E",
transclude: true,
replace: true,
template: '<div>' +
'<span ng-transclude></span>' +
'{{rsLabels.welcome}} {{rsUser.firstName}}!' +
'</div>'
}
})
Run Code Online (Sandbox Code Playgroud)
如果我需要在指令的link函数中使用rootScope,我可以使用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>'
}
})
Run Code Online (Sandbox Code Playgroud)
我的rootScope数据在run函数中定义
.run(function ($rootScope) {
$rootScope.rsLabels = {
welcome: 'Welcome'
};
$rootScope.rsUser = {
firstName: 'Joe'
};
});
Run Code Online (Sandbox Code Playgroud)
谢谢!
kar*_*una 68
你可以这样做:
{{$root.rsLabels.welcome}}
Run Code Online (Sandbox Code Playgroud)
Mik*_*eel 52
从我的实验经验来看,似乎因为所有$ scope最终都继承自$ rootScope,你将能够访问它上面的数据而不需要它作为服务,遵循标准的javascript原型继承规则.如果要将指令中的scope属性设置为false或{},则会发现您无法再访问它.
.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>'
};
});
Run Code Online (Sandbox Code Playgroud)
示例:http://jsbin.com/bequy/1/edit
有时我必须使用 $scope.$root:
app.directive('setOrdinal', function() {
return {
link: function($scope, $element, $attr) {
var steps = $scope.$root.steps;
$scope.$watch(setOrdinal, function(value) {
if (value)
{
// steps code here
}
});
}
};
});
app.controller('stepController', ['$scope', '$rootScope', 'GetSteps', function ($scope, $rootScope, GetSteps) {
var s = $scope;
var r = $rootScope;
s.initialize = function(id)
{
GetSteps.get({id: id}, function(resp){
r.steps = resp.steps;
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84230 次 |
| 最近记录: |