[英]Angularjs undefined variable in controller
我在控制器中有对象属性的问题。 我的工厂返回了一个对象,另一个对象和一个函数。 我可以调用该函数,但是无法访问其他对象属性。 这是我的代码:
我的工厂
app.factory('User', function () {
var User = {};
User.get = function () {
// Call the service... done
User.data = response.data;
};
return User;
});
我的控制器
app.controller('Controller', function ($scope, User) {
$scope.user = User;
console.log(user); // print correct one object with
the function get and data object with user data
console.log(user.data); // undefined
});
谢谢,对不起我的英语灾难
app.factory('User', function () { var User = {}; User.data=null; User.get = function () { // Call the service... done User.data = response.data; }; return User; });
控制器:
app.controller('Controller', function ($scope, User) { $scope.user = User; console.log(user); console.log(user.data); // null,because you did not call the method User.get(); User.get(); console.log(user.data); // this will print the response data which you assign in the User.get() method });
在给定的代码中,User.data将提供对象,但是在您必须调用User.get()
函数之前。
对不起我的英语不好 .....
你有两个问题。 建立工厂的方式伤害了您。 因此,我将整个工厂退回,以便您拥有该功能。 您不必在工厂内部定义用户,因为它是工厂的名称(因此它是一个对象)
app.factory('User', function () {
return {
get: function() {
//return API call
};
});
接下来,定义$ scope.user,然后调用user。 您从未定义过用户,只是$ scope.user。 另外,必须在用户中调用get函数以返回数据。 而且不会
app.controller('Controller', function ($scope, User) {
$scope.user = User.get();
console.log($scope.user); // This will be the data
});
是我的错误,我在另一个控制器中调用User.get();,我的问题是及时的
app.controller('Controller', function ($scope, User) {
$scope.user = User;
setTimeout(function(){
console.log(user.data); // i have data
}, 5000);
});
使用settimeout
不会自动触发$digest
,并且2种方式的数据绑定可能不知道该更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.