AngularJS中未定义对象属性

时间:2015-10-21 00:20:30

标签: javascript angularjs firebase

以下适用于我:

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未定义!为什么会这样?为什么我们可以在视图中调用属性但不在控制器内?如果我想在控制器中调用属性,我该怎么办?

1 个答案:

答案 0 :(得分:4)

可能会发生这种情况,因为在您将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