2014-01-13 5 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 중에서 당신의 SecuritySvc이거나 반환. 난 당신이 방법처럼 그것을해야 생각

<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

확실하지 않음 이 :

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 개체를 반환합니다. 이것은 브라우저 콘솔에서 객체를 볼 수 있지만 이제는 해당 객체의 roleName 및 id에 액세스하는 데 문제가 있습니다. – rlwheeler

+0

오류 메시지가 나타 났습니까? 콘솔 출력을 게시 할 수 있습니다. – michael

+0

출력에 오류가 없지만 데이터를 객체로 취급하지 않는 것 같습니다. 'console.log ($ scope.data.roleName)'콘솔 출력에 정의되지 않았다고 문제를 진단하기 위해 행을 추가했습니다. '$ scope.data'의 콘솔 출력이 ' $ promise : Object $ 해결 됨 : true roleId : 1 roleName : "Admin"' – rlwheeler