【发布时间】:2014-02-01 13:49:21
【问题描述】:
我正在根据用户角色从 api 隐藏或显示元素。当我在代码中设置 data.roleName 时,该指令有效,但是当我尝试通过我的服务设置它时,我需要在加载指令的其余部分之前解决一个承诺,尽管我不断收到“无法读取未定义错误的属性这是代码.
.js
app.directive('restrictTo', ['SecuritySvc', function (SecuritySvc) {
return {
restrict: 'EA',
replace: true,
transclude: true,
scope: {},
controller: ['$scope', '$attrs', '$q', 'SecuritySvc', function ($scope, $attrs, $q, SecuritySvc) {
var defer = $q.defer();
defer.promise.then(function ($scope, SecuritySvc) {
$scope.data = SecuritySvc.getRole();
});
defer.resolve();
if ($scope.data.roleName == $attrs.restrictTo) {
$scope.allowed = true;
} else {
$scope.allowed = false;
}
console.log($scope.data);
}],
template: '<div ng-show="{{ $scope.allowed }}" ng-transclude></div>'
}
}]);
.html
<div restrict-to="customer">
<div class="hero-unit">
<h1>Welcome!</h1>
<p>Hello, valued customer</p>
</div>
</div>
<div restrict-to="Admin">
<div class="hero-unit">
<h1>Admin Tools</h1>
<p>This shouldn't be visible right now</p>
</div>
</div>
【问题讨论】:
标签: javascript angularjs factory promise