Rishabh Jain Rishabh Jain - 5 months ago 15
AngularJS Question

view not updating in angularjs after a promise is resolved

I have a factory which fetches data from server and passes to controllers , many controllers are calling get methods from the factory , but only the scope variable of controller that calls the factory first is changed in view not all... here is my factory code

(function () {
angular.module('myapp').factory('agendaFactory', ['$http', '$q', function ($http, $q) {
var user = "";
var defer = $q.defer();
var agenda = {
getAll: function (tempData, addType) {
$http.post('/api/' + addType + '/getAll', tempData).success(function (data, status) {
console.log(addType, data);
//console.log(status);
defer.resolve(data);

}).error(function (err, status) {
console.log(err, status);
defer.reject(status);
});
return defer.promise;
}
};
return agenda;
}]);
}());


here are the two controllers calling them..

changeData = function (data) {
console.log("called function in liffe");
$scope.lifetimeData = data;
}
agendaFactory.getAll(tempData, addType).then(function (data) {
console.log('lifeData', data);
changeData(data);
return;
}, function (err) {
console.log('today err', err);
})


and second controller

changeData = function (data) {
console.log("called function in year");
$scope.yearData = data;
}
agendaFactory.getAll(tempData, addType).then(function (data) {
console.log('yeardata', data);
changeData(data);
return;
}, function (err) {
console.log('today err', err);
});


but data from only first controller is being updated in the view

Answer

Remove the promise wrapper since $http already returns a promise. Also get rid of the success/error handlers since they're deprecated.

(function () {
angular.module('myapp').factory('agendaFactory', ['$http', '$q', function ($http, $q) {
    var user = "";
    var agenda = {
        getAll: function (tempData, addType) {
            return $http.post('/api/' + addType + '/getAll', tempData);
        }
    };
    return agenda;
}]);
}());

You can then handle the success/error conditions in your controller