gpt4 book ai didi

AngularJS 查询资源一次并在整个应用程序中使用数据

转载 作者:行者123 更新时间:2023-12-02 23:03:53 26 4
gpt4 key购买 nike

我的应用程序有多个 View ,每个 View 都有一个 Controller 。

我有几个返回标准 JSON 数组的 API 资源。每当 View 更改时,就会重新查询资源以获取新数据,这是相当慢的。我更愿意为我的 Controller 提供 API 资源,而无需每次都重新查询。

最好的方法是什么?

最佳答案

如果我理解正确的话,那么这就是服务的用途。它们有点像 Controller 共享数据的中心位置。

我查看了 jsfiddle 以查找本教程中使用的代码:

http://onehungrymind.com/angularjs-communicating-between-controllers/

var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};

sharedService.message = '';

sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};

sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};

return sharedService;
});

function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};

$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}

function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}

function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}

ControllerZero.$inject = ['$scope', 'mySharedService'];

ControllerOne.$inject = ['$scope', 'mySharedService'];

ControllerTwo.$inject = ['$scope', 'mySharedService'];​
<小时/>

编辑

对于资源调用,我现在有一个像这样使用它们的服务。抱歉,它在 CoffeeScript 中

.factory('EventService', (SubEvent, User) ->
subevents = {}

return {
getSubevent: (subevent_id) ->
SubEvent.get {subevent_id: subevent_id}, (subevent) ->

participants = (participant.user for participant in subevent.participants)
User.query {participants: participants}, (users) ->
for user,i in users
subevent.participants[i].user = user

subevents[subevent_id] = subevent
}
)

关于AngularJS 查询资源一次并在整个应用程序中使用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12311778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com