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

前端 未结 5 1006
广开言路
广开言路 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:36

    Using a watch for that is kinda ugly.

    try this:

    datModule.factory('datfactory', function ($http, $q){
    
        this.getlist = function(){            
            return $http.get('http://localhost:61686/getdatlist?format=json',{'Access-Control-Allow-Origin': 'localhost:*'})
                .then(function(response) {
                  console.log(response); //I get the correct items, all seems ok here
                  return response.data.itemsToReturn;
                });            
        }
        return this;
    });
    
    datModule.controller('datlist', function ($scope, datfactory){
        datfactory.getlist()
          .then(function(arrItems){
             $scope.items = arrItems;
           });
    });
    

    This is how you use promises for async matter.

    UPDATE (15.01.2015): Now even sleeker!

提交回复
热议问题