小编典典

在工厂发出GET请求后,AngularJs $ scope不更新

angularjs

我一直在尝试AngularJS进行实验项目,但我遇到了这个问题。在我的html中,我想显示项目列表

Index.html

<h1>Some list</h1>
<div ng-controller="datlist">
    <div ng-repeat="item in items">
        <div>Item description: {{item.description}}</div>
        <div>Item name: {{item.name}}</div>
    </div>
</div>

最初,我只是使用一个简单的控制器来获取信息并使用以下命令更新视图:

controllers.js(原始)

function datlist($scope,$http){
$http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
    success(function(data, status, headers, config) {
        $scope.items=data.itemsToReturn;
        console.log(data);
}).
error(function(data, status, headers, config) {
    console.log("fail");
});

}

这工作得很好,我可以获得项目清单。同时,通过更改我的结构以使用工厂发出相同的请求并将其绑定到$ scope.items,该命令将不起作用。我尝试了许多$
watch的变体,但无法更新$ scope.items。我发现了一些有关$ apply的信息,但我真的不明白如何使用它。

controllers.js(新版本)

var datModule = angular.module('datModule',[]);
datModule.controller('datlist', function ($scope, datfactory){
    $scope.items = datfactory.getlist();
    $scope.$watch($scope.items, $scope.items = datfactory.getlist());
});
datModule.factory('datfactory', function ($http){
    var factory = {};
    factory.getlist = function(){
        $http({method: 'GET', url: 'http://localhost:61686/getdatlist?format=json', headers: {'Access-Control-Allow-Origin': 'localhost:*'}}).
        success(function(data, status, headers, config) {
            console.log(data.itemsToReturn); //I get the correct items, all seems ok here
            return data.itemsToReturn;
        }).
        error(function(data, status, headers, config) {
            console.log("fail");
        });

    }
    return factory;
});

关于这个的任何想法都会很棒。PS:我发现很多帖子都在谈论这个问题,但是没有一个帮助我获得完整的解决方案。

谢谢


阅读 312

收藏
2020-07-04

共1个答案

小编典典

为此使用手表是很丑的。

试试这个:

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;
       });
});

这就是您对异步事务使用promise的方式。

更新(15.01.2015):现在更时尚!

2020-07-04