gpt4 book ai didi

javascript - AngularJS 中 undefined object 属性

转载 作者:行者123 更新时间:2023-11-29 18:03:27 24 4
gpt4 key购买 nike

以下对我有用:

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 未定义!为什么会这样?为什么我们可以在 View 中调用属性,而不能在 Controller 中调用?想调用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 对象绑定(bind)到范围是一个更好的方法。最好只将容器对象绑定(bind)到 $scope

关于javascript - AngularJS 中 undefined object 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33248957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com