使用promise来检索angular指令内的数据

时间:2014-01-13 17:32:39

标签: javascript angularjs factory promise

我正在根据api中的用户角色隐藏或显示元素。当我在代码中设置data.roleName时该指令有效,但是当我尝试通过I服务设置它时,我需要在加载指令的其余部分之前解析一个承诺,虽然我不断得到“无法读取未定义错误的属性这里是代码

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

2 个答案:

答案 0 :(得分:2)

不确定您的SecuritySvc是什么或返回。我想你应该这样做:

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

答案 1 :(得分:2)

如果您不想使用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>'
};

}]);