解决方案在这个小提琴中:
http://jsfiddle.net/BmQuY/3/
var app = angular.module('myApp', []);
app.service('authService', function(){
var user = {};
user.role = 'guest';
return{
getUser: function(){
return user;
},
generateRoleData: function(){
/* this is resolved before the
router loads the view and model.
It needs to return a promise. */
/* ... */
}
}
});
app.directive('restrict', function(authService){
return{
restrict: 'A',
priority: 100000,
scope: false,
compile: function(element, attr, linker){
var accessDenied = true;
var user = authService.getUser();
var attributes = attr.access.split(" ");
for(var i in attributes){
if(user.role == attributes[i]){
accessDenied = false;
}
}
if(accessDenied){
element.children().remove();
element.remove();
}
return function linkFn() {
/* Optional */
}
}
}
});
如果你想在 IE 7 或 8 中使用这个指令,你需要手动删除元素的子元素,否则会抛出错误:
angular.forEach(element.children(), function(elm){
try{
elm.remove();
}
catch(ignore){}
});
可能的用法示例:
<div data-restrict access='superuser admin moderator'><a href='#'>Administrative options</a></div>
使用 Karma + Jasmine 进行单元测试:
注意:done
回调函数仅适用于 Jasmine 2.0,如果您使用的是 1.3,则应使用waitsFor代替。
describe('restrict-remove', function(){
var scope, compile, html, elem, authService, timeout;
html = '<span data-restrict data-access="admin recruiter scouter"></span>';
beforeEach(function(){
module('myApp.directives');
module('myApp.services');
inject(function($compile, $rootScope, $injector){
authService = $injector.get('authService');
authService.setRole('guest');
scope = $rootScope.$new();
// compile = $compile;
timeout = $injector.get('$timeout');
elem = $compile(html)(scope);
elem.scope().$apply();
});
});
it('should allow basic role-based content discretion', function(done){
timeout(function(){
expect(elem).toBeUndefined();
done(); //might need a longer timeout;
}, 0);
});
});
describe('restrict-keep', function(){
var scope, compile, html, elem, authService, timeout;
html = '<span data-restrict data-access="admin recruiter">';
beforeEach(function(){
module('myApp.directives');
module('myApp.services');
inject(function($compile, $rootScope, $injector){
authService = $injector.get('authService');
timeout = $injector.get('$timeout');
authService.setRole('admin');
scope = $rootScope.$new();
elem = $compile(html)(scope);
elem.scope().$apply();
});
});
it('should allow users with sufficient priviledsges to view role-restricted content', function(done){
timeout(function(){
expect(elem).toBeDefined();
expect(elem.length).toEqual(1);
done(); //might need a longer timeout;
}, 0)
})
});
元素的通用访问控制指令,不使用 ng-if(仅从 V1.2 开始 - 目前不稳定)或 ng-show,它实际上不会从 DOM 中删除元素。