分享AngularJS控制器之间的数据,但具有Ajax调用来共享数据 [英] Sharing data between AngularJS controllers but having the shared data come from an Ajax call

查看:128
本文介绍了分享AngularJS控制器之间的数据,但具有Ajax调用来共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到了如何在下面的人为的例子使用共享服务,共享两个AngularJS控制器之间的数据:

I've figured out how to share data between two AngularJS controllers using a shared service in the contrived example below:

(正常工作的小提琴

var app = angular.module('myApp', []);

app.factory('UserData', function() {
    var data = {foo: 'bar'};

    return {
        getData: function() {
            console.log('getData');
            return data;
        },
        setData: function(newData) {
            data = newData;
        }
    };
});

function MainCtrl($scope, UserData) {
    console.log('MainCtrl');
    console.log(UserData.getData());
}
MainCtrl.$inject = ['$scope', 'UserData'];

function JobListCtrl($scope, UserData) {
    console.log('JobListCtrl');
    console.log(UserData.getData());
}
JobListCtrl.$inject = ['$scope', 'UserData'];

我的问题是,我想在的UserData 中的数据来自一个Ajax调用(presumably使用 $ HTTP )。

My issue is that I would like the data held in UserData to come from an Ajax call (presumably using $http).

我试着做了的UserData 工厂函数Ajax调用,但由于它的异步运行, MainCtrl JobListCtrl 的UserData 服务,实际上它具有任何数据之前被执行。

I tried doing the Ajax call in the UserData factory function but, since it's running asynchronously, MainCtrl and JobListCtrl are executed before the UserData service actually has any data in it.

有人可以给我如何设置了一些方向?

Can someone give me some direction about how to set that up?

推荐答案

我创建了这个例子,说明如何为获取,存储和共享数据(模型)不同的控制器而不失去其绑定功能。

I've created this example that shows how to fetch, store and share data (models) across different controllers without loosing its bindable functionality.

活生生的例子: http://pablodenadai.github.io/SharingModelsAngularJS/

来源$ C ​​$ C 1:(资源和模型抽象)<一个href=\"https://github.com/pablodenadai/SharingModelsAngularJS/blob/master/app/scripts/controllers/main.js\" rel=\"nofollow\">https://github.com/pablodenadai/SharingModelsAngularJS/blob/master/app/scripts/controllers/main.js

回购: https://github.com/pablodenadai/SharingModelsAngularJS

希望它帮助。

这篇关于分享AngularJS控制器之间的数据,但具有Ajax调用来共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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