【问题标题】:angularjs Watching rootscope changesangularjs 观察 rootscope 变化
【发布时间】:2013-06-02 23:08:44
【问题描述】:

我正在尝试绑定到 rootscope,以便在用户登录时可以在不同的服务器上设置存在。 这是我的模块。

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 只是此应用程序实例的根范围,您将希望使用服务/工厂,并以某种方式在某处保留存在更改。
  • @xmltechgeek 你能举例说明如何正确地做到这一点吗?这听起来像是我需要学习的东西,谢谢
  • 尝试将 $rootScope.currentUser 设置为错误时的虚拟值,并检查是否是原因。

标签: javascript angularjs


【解决方案1】:

语法是$rootScope.$watch('currentUser') 而不是$rootScope.$watch($rootScope.currentUser)

【讨论】:

  • 嗨,你在哪里写这个声明?
  • 注入了 $rootScope 的任何地方。
【解决方案2】:

需要更改 $rootScope.currentUser 以便您能够注意到其中的任何更改。您已经共享了代码。

$rootScope.currentUser 的更改也需要在 angularJS 循环 (http://docs.angularjs.org/guide/concepts) 内进行。如果是在外部完成,您可以调用 $digest (http://docs.angularjs.org/api/ng.$rootScope.Scope#$digest)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-15
    • 2018-04-10
    • 2013-10-18
    • 2016-05-30
    • 1970-01-01
    • 2013-01-23
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多