Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 – 使用服务以角度在多个控制器之间共享ajax数据全部内容,希望文章能够帮你解决angularjs – 使用服务以角度在多个控制器之间共享ajax数据所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。