简体   繁体   中英

Angularjs undefined variable in controller

I have a problem in controller with the properties of object. My factory return one object with another object and one function. I can call the function but i can't access in another object properties. Here is my code:

My factory

app.factory('User', function () {

var User = {};

User.get = function () {
   // Call the service... done
   User.data = response.data;        
};

return User;
});

My controller

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

});

Thanks, and sorry for my english disaster

 app.factory('User', function () { var User = {}; User.data=null; User.get = function () { // Call the service... done User.data = response.data; }; return User; }); 

Controller:

 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 }); 

In the code you given, User.data will give the object but before you have to call User.get() function.

Sorry for my English .....

You have two problems. The way you set up your factory is hurting you. So I would return the whole factory so you have that function. You don't have to define User inside the factory because it is the name of the factory (therefore it is an object)

app.factory('User', function () {

return {
    get: function() {
        //return API call
    };
});

Next, you are defining $scope.user and then calling user. You never defined user, just $scope.user. Also, you must call the get function in user to return data. And it will not be

app.controller('Controller', function ($scope, User) {
$scope.user = User.get();

console.log($scope.user);  // This will be the data

});

Is my error, i call in another controller User.get();, My problem is in time

app.controller('Controller', function ($scope, User) {
   $scope.user = User;

   setTimeout(function(){
       console.log(user.data); // i have data
   }, 5000);


});

Use settimeout will not auto fire the $digest and the 2 way data binding may not aware of the update.

  1. user q and promise instead of timeout
  2. if timeout is required, use $timeout instead of settimeout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM