【问题标题】:Object property is undefined in AngularJSAngularJS 中未定义对象属性
【发布时间】:2015-10-21 00:20:30
【问题描述】:

以下对我有用:

HTML:

{{user.uid}}

JS:

"use strict";

app.controller('Ctrl', function($scope, Auth) {

$scope.user = Auth.user;
});

但是

HTML:

{{uid}}

JS:

app.controller('Ctrl', function($scope, Auth) {
 $scope.uid = Auth.user.uid;
});

不起作用,这是因为 Auth.user.uid 未定义!为什么会这样?为什么我们可以在视图中调用属性,而不能在控制器中调用?如果我想在控制器中调用一个属性怎么办?

【问题讨论】:

  • Auth.user 是否返回承诺?
  • @Claies 我的猜测是其他地方正在异步填充Auth.user。它本身并不是一个承诺
  • @Phil 是的,就像来自$http 的承诺。不管怎样,没有看到Auth的代码,我们只能猜测真正的问题。
  • 我的坏人——我很确定我和这里有同样的问题:stackoverflow.com/questions/25450325/…——我应该删除这个问题吗?

标签: javascript angularjs firebase


【解决方案1】:

这很可能发生,因为在您将Auth.user.uid 分配给范围时,该属性不存在。它稍后会分配给user 对象,但是因为您已将值直接映射到$scope,所以它不会按照您希望的方式更新。以下是如何发生这种情况的示例:

.service('Auth', function($http){
    this.user = {};
    // this server call takes some amount of time to complete,
    // and until it does user.uid is undefined
    var self = this;
    $http.get('http://someurl', function(result){
        self.user.uid = result.uid;
    });
});

.controller('MyCtrl', function($scope, Auth){
    // this is called before the $http call is completed inside Auth
    $scope.uid = Auth.user.uid;

    // this is also called before the $http call completed, but because user exists, its children cause a scope change and notification
    $scope.user = Auth.user;
});

现在,通过将user 对象绑定到作用域来实现它是一种更好的方法。最好只将容器对象绑定到$scope

【讨论】:

  • 澄清一下,是$http promise 解析触发了摘要循环,从而更新了模板。 JavaScript 的对象引用意味着Auth.user$scope.user 是同一个对象
  • 只是想知道 - 为什么只将容器对象绑定到 $scope 是一种好习惯?
  • 主要是因为您保证您尝试访问的 $scope 级别(对于像 ng-model 这样的东西也是必不可少的)。只需研究角度范围层次结构的工作原理,以及为什么点很重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多