对象 属性 在 AngularJS 中未定义
Object property is undefined in AngularJS
以下对我有用:
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没有定义!为什么会这样?为什么我们可以在视图中调用属性,而不能在控制器中调用?想调用controller内部的属性怎么办?
这很可能发生,因为在您将 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
.
以下对我有用:
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没有定义!为什么会这样?为什么我们可以在视图中调用属性,而不能在控制器中调用?想调用controller内部的属性怎么办?
这很可能发生,因为在您将 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
.