整个应用AngularJS查询一次资源和使用数据 [英] AngularJS query resource once and use data throughout app

查看:115
本文介绍了整个应用AngularJS查询一次资源和使用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有几个观点,每个视图都有一个控制器。

My App has several views,each view has a controller.

我有几个API返回的资源JSON标准的一个arrays.Whenever观的变化,资源重新查询新的数据是相当缓慢。我想preFER提供本人的API资源控制器而无需每次都重新查询。

I have several API resources returning standard JSON arrays.Whenever a view changes,the resources are re-queried for new data which is fairly slow. I'd prefer to provide my controllers with the API resources without requerying each time.

最新最好的方式做到这一点?

Whats the best way to do this?

推荐答案

如果我理解正确,那么这是什么样的服务是。他们有点像为控制器共享数据的中央位置。

If I understand correctly then this is what services are for. They're kind of like a central place for controllers share data.

我查了一下的jsfiddle在本教程中使用的code:

I looked over the jsfiddle for the code used in this tutorial:

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的

For resource calls, I have a service right now that uses them like this. Sorry that its in 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查询一次资源和使用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆