Angularjs 控制器中的未定义变量

Angularjs undefined variable in controller

本文关键字:未定义 变量 控制器 Angularjs      更新时间:2023-09-26

我在控制器中遇到了对象属性的问题。我的工厂返回一个对象,其中包含另一个对象和一个函数。我可以调用该函数,但无法访问另一个对象属性。这是我的代码:

我的工厂

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()函数之前。

对不起我的英语.....

你有两个问题。你建立工厂的方式正在伤害你。所以我会返回整个工厂,这样你就有了这个功能。您不必在工厂内定义 User,因为它是工厂的名称(因此它是一个对象)

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 路数据绑定可能不知道更新。

  1. 用户 q 和承诺而不是超时
  2. 如果需要超时,请使用$timeout而不是设置超时。