angularjs – 使用服务以角度在多个控制器之间共享ajax数据

前端之家收集整理的这篇文章主要介绍了angularjs – 使用服务以角度在多个控制器之间共享ajax数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨我有两个控制器

pqsAppModule.controller('NotificationBoxController',function($scope,items) {
    $scope.list = items.list();
})

pqsAppModule.controller('NotificationController',items) {
    $scope.list = items.list();
})

我需要创建一个“项目”服务,该服务将执行ajax请求并返回任何将注入它的控制器的数据.我希望,查询只进行一次,所有控制器之间共享项目.

pqsAppModule.factory('items',function($http) {
    var items = [];
    var itemsService = {};
    $http.get('api/notification').then(function(response){
        items = response.data;
    });

    itemsService.list = function() {
        return items;
    };

    return itemsService;
});

但我不明白为什么angular发出请求并接收数据,但控制器中的所有项都是空的.

解决方法

这是因为工厂应该以不同的方式定义.

(我只使用虚拟URL来通过异步方式加载数据)

HTML

<div ng-controller="NotificationBoxController">
    <button ng-click="showMe();">press  me</button>
    <pre>NotificationBoxController: {{items.getList()|json}}</pre>
</div>

<div ng-controller="NotificationController">
    <pre>NotificationController: {{items.getList()|json}}</pre>
</div>

JS

var pqsAppModule = angular.module('myApp',[]);
pqsAppModule.controller('NotificationBoxController',items) {
    $scope.items = items;

    $scope.showMe= function(){
     items.query();   
    }
});

pqsAppModule.controller('NotificationController',items) {
    $scope.items = items;
});


pqsAppModule.factory('items',function ($http) {

    var current = {};    

    var address = 'Singapore,SG,Singapore,153 Bukit Batok Street 1';
    var URL = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=true';

       var factory = {            
           query: function () {                
                var data = $http({method: 'GET',url:URL}).then(function (result) {
                           current = result.data.results[0];                            
                        },function (result) {
                            alert("Error: No data returned");
                        });  
            },getList: function () {                
               return current;
            }
       }       
        return factory; 
  });

演示Fiddle

在这个例子中,我们从两个控制器的HTML中调用items.getList().但是如果我们想通过控制器更新模型,我们需要一个像$watch这样的监听器

猜你在找的Angularjs相关文章