angularjs – 使用服务以角度在多个控制器之间共享ajax数据
发布时间:2020-12-17 18:07:41 所属栏目:安全 来源:网络整理
导读:嗨我有两个控制器 pqsAppModule.controller('NotificationBoxController',function($scope,items) { $scope.list = items.list();}) 和 pqsAppModule.controller('NotificationController',items) { $scope.list = items.list();}) 我需要创建一个“项目”服
嗨我有两个控制器
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这样的监听器 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |