2014-01-13 30 views
1

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

回答

2

如果你不想使用Q /延迟,并使用$资源,你可以这样来做:

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

}]);

+1

您是否需要将SecuritySvc注入指令和控制器中? – Askdesigners

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

SecuritySvc返回一个带有id和一个roleName的json对象。这工作,我可以看到浏览器控制台中的对象,但现在我无法访问该对象的角色名称和ID。 – rlwheeler

+0

你有没有收到任何错误讯息?也许你可以发布控制台输出。 – michael

+0

输出中没有错误,但它似乎不把数据当作一个对象,我已经添加了一行来诊断问题'console.log($ scope.data.roleName)'控制台输出说它是未定义的。 'scope.data'的控制台输出是' $ promise:Object $ resolved:true roleId:1 roleName:“Admin”' – rlwheeler