AngularJs $scope doesn't update after a GET request on a factory

前端 未结 5 977
广开言路
广开言路 2020-12-31 14:10

I have been trying AngularJS for a experimental project and I came along with this problem. In my html I want to display a list of items

Index.html<

5条回答
  •  借酒劲吻你
    2020-12-31 14:41

    The issue is nothing to do with the scope digest cycle. You are trying to return from inside a callback directly, which is not asynchronously possible.

    I recommend you either use a promise, or return the http promise directly.

    var factory = {};
    factory.getlist = function(){
        return $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}});
    
    }
    return factory;
    

    To return the promise directly, and handle the success/fail at factory.getlist().success()

    Alternatively, use your own promise if you want to wrap additional logic around the request.

    var datModule = angular.module('datModule',[]);
    
    datModule.controller('datlist', function ($scope, datfactory){
        $scope.items = [];
        datfactory.getlist().then(function(data) { $scope.items = data });
    });
    
    datModule.factory('datfactory', function ($http, $q){
        var factory = {};
        factory.getlist = function(){
            var defer = $q.defer();
            $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
            success(function(data) {
                // alter data if needed
                defer.resolve(data.itemsToReturn);
            }).
            error(function(data, status, headers, config) {
                defer.reject();
            });
            return defer.promise;
        }
        return factory;
    });
    

提交回复
热议问题