gpt4 book ai didi

javascript - 使用 promise 在 Angular Directive(指令)中检索数据

转载 作者:行者123 更新时间:2023-11-30 10:22:09 24 4
gpt4 key购买 nike

我正在研究根据 api 的用户 Angular 色隐藏或显示元素。当我在代码中设置 data.roleName 时该指令有效但是当我尝试通过我的服务设置它时我需要在加载指令的其余部分之前解决一个 promise 尽管我不断收到“无法读取未定义错误的属性这是代码.

.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>

最佳答案

如果你不想使用 Q/defer 并且正在使用 $resource 你可以这样做:

app.directive('restrictTo', ['SecuritySvc', function (SecuritySvc) {
return {
restrict: 'AE',
replace: true,
transclude: true,
scope: {},
controller: ['$scope', '$attrs', 'SecuritySvc', function ($scope, $attrs, SecuritySvc) {
$scope.allowed = false;
SecuritySvc.getMyRole().$promise.then(function (data,attrs) {
if (data.roleName == $attrs.restrictTo) {
$scope.allowed = true;
} else {
$scope.allowed = false;
}
});
}],
template: '<div ng-show="allowed" ng-transclude></div>'
};

}]);

关于javascript - 使用 promise 在 Angular Directive(指令)中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21097677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com