2

내가 몇 가지 속성을 가진 아주 간단한 서비스를 가지고 있다고 가정 해 보겠습니다. 컨트롤러에서 서비스를 사용하는 경우 서비스의 속성을 범위에 배치하여 내 뷰에 바인딩되고 뷰를 업데이트합니다. 이것은 내가 기대하는 행동입니다. 그러나 동일한 서비스의 속성이 컨트롤러의 범위 밖에있는 지시문에서 수정되면보기가 업데이트되지 않습니다 (컨트롤러의 범위에서 시계가 업데이트되도록 트리거하지 않는 한). 분명히 내가 여기에서 빠뜨린 근본적인 것이 있지만, 검색 서치 검색은 나를 답으로 이끌지 못했다.angularjs - 컨트롤러 범위에서 서비스 속성보기 ... 지침에서 변경 ... 업데이트하지 않습니까?

다음은 JSFiddle의 예입니다.

app = angular.module('app', []); 
// simple service to track application's logon status 
app.factory('AuthService', function() { 
    var status = { 
     isLoggedIn: false 
    }; 

    return { 
     status: status, 
     login: function() { 
      status.isLoggedIn = true; 
      console.log('user logged in'); 
     }, 
     loggedIn: function() { 
      return status.isLoggedIn; 
     }, 
     logout: function() { 
      status.isLoggedIn = false; 
      console.log('user logged out'); 
     } 
    } 
}); 

app.controller('AuthViewCtrl', function ($scope, AuthService) { 
    // bind some service attributes, functions to the scope so that we can use them in our view 
    $scope.loggedIn = AuthService.loggedIn; 
    $scope.login = AuthService.login; 
    $scope.logout = AuthService.logout; 
    $scope.stat = AuthService.status; 
}); 

// a simple directive to allow elements to log out of the app on click 
app.directive('appLogout', function (AuthService) { 
    return function (scope, element) { 
     element.bind('click', function() { 
      AuthService.logout(); 
     }); 
    } 
}); 

// a simple directive to allow elements to log into the app on click 
app.directive('appLogin', function (AuthService) { 
    return function (scope, element) { 
     element.bind('click', function() { 
      AuthService.login(); 
     }); 
    } 
}); 

그리고 첨부 된 HTML : 당신이 시작할 때

<div ng-app="app"> 
    <div ng-controller="AuthViewCtrl"> 
     <strong>Are we logged in?</strong> 
     <ul> 
      <li>service func on scope: <strong>{{ loggedIn() }}</strong></li> 
      <li>service prop on scope: <strong>{{ stat.isLoggedIn }}</strong></li> 
     </ul> 

     <button ng-click="login()">log in from controller scope</button> 
     <button ng-click="logout()">log out from controller scope</button> 
     <button ng-click="loggedIn()">call AuthService.loggedIn()</button> 
    </div> 

    <button app-login>log in from directive</button> 
    <button app-logout>log out from directive</button> 
</div> 

이 응용이 로그 아웃됩니다. 범위에 게시 된 서비스 기능을 호출하는 "컨트롤러에서 로그인 [/ 아웃]"하면 감시 된 서비스 값이보기에서 즉시 업데이트됩니다. 그러나 "지시어에서 로그인 [/ 아웃]"을 누르면 감시 된 서비스 값이 업데이트되지 않습니다 (범위 내에서 AuthService.loggedIn()을 호출하면 업데이트됩니다).

제 질문은이 문제를 해결하는 가장 좋은 방법은 무엇입니까? 나는 봉사 가치를 보면서 어디를 떠나 갔는가?

감사합니다, 아담

답변

1

문제는 당신이 각의 "외부"서비스를 호출하고 있다는 것입니다 :

:

element.bind('click', function() { 
     AuthService.login(); 
    }); 

그래서, 당신은 $apply에 전화를 포장 할 필요가

element.bind('click', function() { 
     scope.$apply(function() { 
      AuthService.login(); 
     }); 
    }); 

피들 : http://jsfiddle.net/SAsBa/46/

+0

가장 확실합니다! 고맙습니다, @ dnc253. – OakBehringer

관련 문제