精简版:
此 plunkr 页面将角色设置为未定义,因此不会显示应显示的内容,但当通过单击触发时,角色似乎是正确的。
示例 plunkr 以强调问题:
http://plnkr.co/edit/QHUpCv?p=preview
完整版:
我有一个静态菜单,对于我的应用程序中的所有视图都是持久的。出于显而易见的原因,我想在显示之前解决 XHR 请求。
尝试使用 an-init,但它只是使函数异步调用,尝试使用来自 $q 对象的承诺,但这也无济于事。
html:
<div ng-app="myApp" ng-controller="homeCtrl">
<div ng-init="loadCurrentUser()" ng-include src="'partials/menu.html'"></div>
<ng-view></ng-view>
</div>
控制器:
controller('homeCtrl', function($scope, $route, $location, authService){
$scope.loadCurrentUser = authService.loadCurrentUser;
$scope.model = {message : 'Hello Oleg'};
$scope.logCurrentUser = function(){
var user = authService.getUser();
console.log(user);
}
});
服务:
authServ.loadCurrentUser = function () {
alert('here');
// var defer = $q.defer();
return $http.get('/users/me', {
withCredentials: true
}).
success(function (data, status, headers, config) {
console.log(data);
that.currentUser.company = {};
that.currentUser.company.id = that.currentUser.company.id ? that.currentUser.company.id : data.main_company;
that.currentUser.companies = [];
for (var i in data.roles) {
that.currentUser.companies[data.roles[i]['company']] = data.roles[i]['company_name'];
if (data.roles[i]['company'] == that.currentUser.company.id){
that.currentUser.role = data.roles[i]['role_type'];
that.currentUser.company.name = data.roles[i]['company_name'];
// console.log(that.currentUser.role);
}
}
// defer.resolve(data);
// defer.resolve();
}).
error(function (data, status, headers, config) {
that.currentUser.role = 'guest';
that.currentUser.company = 1;
defer.reject("reject");
});
// return defer.promise;
}
限制角色访问级别指令:
angular.module('myApp.directives', []).
directive('restrict', function(authService){
return{
restrict: 'A',
prioriry: 100000,
scope: {
// : '@'
},
link: function(){
// alert('ergo sum!');
},
compile: function(element, attr, linker){
var user = authService.getUser();
if(user.role != attr.access){
console.log(attr.access);
console.log(user.role);//Always returns undefined!
element.children().remove();
element.remove();
}
}
}
});