简体   繁体   中英

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

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

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