2013-08-14 2 views
2

내 SPA의 모든보기에있는 영구 메뉴를 포함하려면 ng-include를 사용하고 있습니다.XHR에서 검색 한 데이터를 사용하는 지시문이있는 템플릿에 ng-include 사용

문제는 각 사용자 유형 (관리자, 게스트, 사용자 등)마다이 메뉴에 다른 옵션과 내용을 표시하려고하기 때문에 먼저 서비스 기능인 authService.loadCurrentUser가 먼저 해결되어야합니다.

이 콘텐츠를 쉽고 편리하게 관리하기 위해 필자는 필요한 액세스 수준을 가진 속성을 취하는 간단한 지시문을 만들고 지정된 사용자의 권한이 해당 요소의 컴파일 단계 일 때 컴파일했습니다. 충분하지 않으면 요소를 제거하고 그 요소는 자식입니다.

그래서 ng-include를 routeProvider 함수를 사용하여 만들려고 노력한 결과, ng-init을 사용하려고 시도했지만 아무 것도 작동하지 않는 것처럼 보였습니다. 사용자 역할은 로깅 할 때 정의되지 않은 채로 남아 있습니다. 그것.

나는 새로운 접근 방식을 시도하고 전체 메뉴를 각 사용자 유형에 적합한 템플릿을 포함하는 지시문으로 만들려고 생각하지만 먼저이 문제를 해결하려고합니다.

지침 :

'use strict'; 
/* Directives */ 
angular.module('myApp.directives', []). 
directive('restrict', function(authService){ 
    return{ 
     restrict: 'A', 
     prioriry: 100000, 
     scope: { 
      // : '@' 
     }, 
     link: function(){ 
      // alert('ergo sum!'); 
     }, 
     compile: function(element, attr, linker){ 
      var user = authService.getUser(); 
       if(user.role != attr.access){ 
       console.log(attr.access); 
       console.log(user.role);//Always returns undefined! 
        element.children().remove(); 
        element.remove();   
       } 

     } 
    } 
}); 

서비스 :

'use strict'; 
/* Services */ 
angular.module('myApp.services', []). 
factory('authService', function ($http, $q) { 
    var authServ = {}; 
    var that = this; 
    that.currentUser = {}; 
    authServ.authUser = function() { 
     return $http.head('/users/me', { 
      withCredentials: true 
     }); 
    }, 
    authServ.getUser = function() { 
     return that.currentUser; 
    }, 
    authServ.setCompany = function (companyId) { 
     that.currentUser.company = companyId; 
    }, 
    authServ.loadCurrentUser = function() { 
     var defer = $q.defer(); 
     $http.get('/users/me', { 
      withCredentials: true 
     }). 
     success(function (data, status, headers, config) { 
      console.log(data); 
      that.currentUser.company = {}; 
      that.currentUser.company.id = that.currentUser.company.id ? that.currentUser.company.id : data.main_company;    
      that.currentUser.companies = []; 
      for (var i in data.roles) { 
       that.currentUser.companies[data.roles[i]['company']] = data.roles[i]['company_name']; 
       if (data.roles[i]['company'] == that.currentUser.company.id){ 
        that.currentUser.role = data.roles[i]['role_type']; 
        that.currentUser.company.name = data.roles[i]['company_name']; 
        // console.log(that.currentUser.role); 
       } 
      } 
      // defer.resolve(data); 
      defer.resolve(); 
     }). 
     error(function (data, status, headers, config) { 
      that.currentUser.role = 'guest'; 
      that.currentUser.company = 1; 
      defer.reject("reject"); 
     }); 
    return defer.promise; 
    } 

    return authServ; 
}); 

메뉴 컨트롤러 :

angular.module('myApp.controllers', []). 
controller('menuCtrl', function($scope, $route, $location, authService){ 
    //TODO: Check if this assignment should be local to each $scope func in order to be compliant with 2-way data binding 
    $scope.user = authService.getUser(); 
    console.log($scope.user); 
    // $scope.companies = $scope.user.companies; 
    $scope.companyOpts = function(){ 
     // var user = authService.getUser(); 
     if(typeof $scope.user.company == 'undefined') 
      return; 

      var companies = []; 
      companies[$scope.user.company.id] = $scope.user.company.name; 
      for(var i in $scope.user.companies){ 
       if(i != $scope.user.company.id){ 
        companies[i] = $scope.user.companies[i];  
       } 
      } 
      // console.log(companies); 
      // if(nonCurrentComapnies.length > 0){ 
       console.log(companies); 
       return companies; 
      // } 
    } 



    $scope.$watch('user.company.name', function(company){ 
     for(var i in $scope.user.companies) 
      if(company == $scope.user.companies[i].id) 
       authService.setCompany(i); 
    }); 
    $scope.$watch(function(){return authService.getUser().company; }, function(company){ 
     //Refresh the page on company change here, first time, and each time the user changes the select 
     // $scope.companyOpts(); 
     // $scope.currentComapany = company; 
    }) 
;}) 

홈페이지 SPA HTML 페이지 :

<div ng-init="authservice.loadCurrentUser" ng-include src="'partials/menu.html'"></div> 
단지 관리자에 표시되어야합니다

메뉴 요소 : 어떤 도움을 사전에

<ul class="left" restrict access="admin"> 
    <li>You are the admin!</li> 
</ul> 

감사합니다!

+0

컨트롤러 코드를 게시하십시오. –

+0

게시 됨, 관련성이있는 것은 확실하지 않습니다. –

+0

관련성이 확실하고'ng-init = "authservice.loadCurrentUser"'를 사용하고 있으므로'authservice'를'$ scope'에 첨부해야합니다. 그것을 가지고 있다면,'authservice.loadCurrentUser'는 호출되지 않을 것입니다. 또한, 실제로 ng-init = "authservice.loadCurrentUser()"'를 사용하여 실제로 함수를 호출해야합니다. –

답변

1

나는 개인적으로 "반대"방식을 사용합니다. 어떤 의미 : 나는 사용자 역할이 "관리자"또는 "사용자"등 경우에 메뉴를 추가합니다 ...

이 방법, 당신은 "제한"지시문이 같은 작업을 수행 할 수 있습니다

... 
    var roleListener = $scope.$watch('user.role', function (newVal, oldVal) { 
     if (newVal == $scope.access) { 
      // add the menu items 
      // supposed that loadcurrentuser be called only once 
      // we should clear the watch 
      roleListener(); 
     } else { 
      // personally, I would remove the item here too 
      // so the menu would be added or removed when user.role update 
     } 
    }); 
    ... 

한가지 더 바로 사용자 역할에 메뉴 기반을 표시를 위해,이 같은 ngSwitch, 뭔가를 사용할 수 있습니다

<ul class="left" ng-switch="user.role"> 
     <li ng-switch-when="admin">You are the admin!</li> 
     <li ng-switch-when="user">You are the user!</li> 
     <li ng-switch-default><img src="some-thing-running.gif"/>Your menu is loading, please wait...</li> 
    </ul> 

를 그리고 마법 AngularJS와 당신을 위해 메뉴를 렌더링 바인딩하자!

0

authServ에 대한 호출입니다.인 getUser 또한 내부적으로 호출하여 약속을 반환해야

authServ.loadCurrentUser 
사용자 컨텍스트는 사용자 컨텍스트와 다른 API 호출이 항상 돌아 해결하고 방지하기 위해 존재하는지 확인하기 위해 약간 수정해야

:

defer.resolve(that.currentUser); 

사용자 컨텍스트 로딩은 앱의 승인을 가능하게하기 때문에 조기에 완료되어야합니다. 이 목적으로 app.run 함수를 사용할 수 있습니다.

다른 사람들에게 도움이되기를 바랍니다.

관련 문제