我正在根据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>
您是否需要将SecuritySvc注入指令和控制器中? – Askdesigners