programing

angularjs 루트스코프 변화 감시

madecode 2023. 3. 4. 15:20
반응형

angularjs 루트스코프 변화 감시

사용자가 로그인할 때 다른 서버에 존재감을 설정할 수 있도록 루트 범위에 바인드하려고 합니다.제 모듈입니다.

angular.module('presence', 
  [
  ]
)

.run(function ($rootScope) {
  $rootScope.$watch($rootScope.currentUser, function () {
    console.log('change currentUser')
    console.log($rootScope.currentUser)
    presence.setGlobal({
      u: $rootScope.currentUser,
      s: 'on'
    })
  })
})

컨트롤러는 없습니다.이는 사용자의 글로벌 존재에 관한 것일 뿐 DOM과는 무관하기 때문입니다.

이것은 동작하지 않습니다.시계는 한 번 실행되지만 이후 변경 시에는 다시 실행되지 않습니다.도와주셔서 고마워요.

편집: 로그인 코드는 다음과 같습니다.

  $scope.login = function() {
    $http.post('http://localhost:3000/login', $scope.user).success(function(res, status) {
      if (res && res._id) {
        $rootScope.currentUser = res
      }
    }).error(function(res, status) {
      $scope.error = res.err
    });
  };

이 코드는, DOM 로 올바르게 갱신된다.html 의 유저명이 표시됩니다.다음은 예를 제시하겠습니다.

a.user(ui-if="currentUser", ng-href="/user/{{currentUser._id}}") {{currentUser.username}}

구문은$rootScope.$watch('currentUser')것은 아니다.$rootScope.$watch($rootScope.currentUser)

뭔가 바뀌어야 해$rootScope.currentUser어떤 변화도 알아차릴 수 있도록 하기 위해서요.당신은 그것에 대한 코드를 공유했습니다.

에 대한 변경도 있습니다.$rootScope.currentUser각도 안에서 일어날 필요가 있다JS 루프(http://docs.angularjs.org/guide/concepts)).외부로 문의하실 경우 $1900(http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest))으로 문의하실 수 있습니다.

언급URL : https://stackoverflow.com/questions/16888166/angularjs-watching-rootscope-changes

반응형