Using a promise for retrieving data inside angular directive

故事扮演 提交于 2019-12-23 03:36:13

问题


I am working on hiding or showing elements based on user role from an api. The directive works when I set the data.roleName in the code but when I try to set it by I service I need to resolve a promise before loading the rest of the directive though I keep getting "cannot read property of undefined errors Here's the code.

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

回答1:


If you dont want to use Q/defer and are using $resource you can do it this way:

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>'
};

}]);




回答2:


Not sure what your SecuritySvc is or returns. I think you should do it in a way like this:

    var defer = $q.defer();
    defer.resolve(SecuritySvc.getRole());
    defer.promise.then(function (data) {
        $scope.data = data;
        if ($scope.data.roleName == $attrs.restrictTo) {
            $scope.allowed = true;
        } else {
            $scope.allowed = false;
         }
        console.log($scope.data);
    });


来源:https://stackoverflow.com/questions/21097677/using-a-promise-for-retrieving-data-inside-angular-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!