我正在根據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