2014-01-13 29 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