I have this factory:
app.factory('user', function($http) {
var state; // logged state
function login(data) {
$http.post('/login', {..}).success(function(data) {
this.state = 1;
});
console.log(this.state); // undefined
return this.state;
}
return {
login: login
}
});
When I try to use it inside a controller:
app.controller('TestCtrl', function(user) {
this.login = function() {
alert(user.login(this.data)); // undefined
};
});
What am I doing wrong? I've got same code in other project and it's working there.
this
in the success callback does not refer to the service. That's why you got an undefined
, besides the fact that the console.log
is outside the callback.
You should have better results if you cache this
at the beginning of the service:
var service = this;
And in the callback, store state
in service
:
service.state = 1;
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.