相关疑难解决方法(0)

AngularJS:使用共享服务(使用$ resource)在控制器之间共享数据,但是如何定义回调函数?

注意:我还在AngularJS邮件列表上发布了这个问题:https://groups.google.com/forum/#!topic / angular/UUC8_pZsdn2U

大家好,

我正在构建我的第一个AngularJS应用程序,并且我不熟悉Javascript,所以任何指导都将非常感谢:)

我的应用程序有两个控制器,ClientController和CountryController.在CountryController中,我正在从使用$ resource对象的CountryService中检索国家列表.这很好,但我希望能够与ClientController共享国家/地区列表.经过一些研究,我读到我应该使用CountryService来存储数据并将该服务注入两个控制器.

这是我以前的代码:

CountryService:

services.factory('CountryService', function($resource) {
    return $resource('http://localhost:port/restwrapper/client.json', {port: ':8080'});
});
Run Code Online (Sandbox Code Playgroud)

CountryController:

//Get list of countries         
//inherently async query using deferred promise
$scope.countries = CountryService.query(function(result){       
        //preselected first entry as default
    $scope.selected.country = $scope.countries[0];  
});
Run Code Online (Sandbox Code Playgroud)

在我改变之后,它们看起来像这样:

CountryService:

services.factory('CountryService', function($resource) {
    var countryService = {};

    var data;
    var resource = $resource('http://localhost:port/restwrapper/country.json', {port: ':8080'});

    var countries = function() {
        data = resource.query();
        return data;
    }

    return {
        getCountries: function() {
            if(data) {
                console.log("returning cached …
Run Code Online (Sandbox Code Playgroud)

javascript angularjs

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

angularjs ×1

javascript ×1