GVKun编程网logo

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

7

在这篇文章中,我们将为您详细介绍AngularJS:使用共享服务的内容,并且讨论关于带有$resource在控制器之间共享数据,但是如何定义回调函数?的相关问题。此外,我们还会涉及一些关于ajax–在

在这篇文章中,我们将为您详细介绍AngularJS:使用共享服务的内容,并且讨论关于带有$ resource在控制器之间共享数据,但是如何定义回调函数?的相关问题。此外,我们还会涉及一些关于ajax – 在angular.js中的控制器之间共享变量、angularjs – Angular docs:如何在控制器之间共享无状态/有状态代码?、angularjs – 使用服务以角度在多个控制器之间共享ajax数据、angularjs – 在不同模块中的指令和控制器之间共享数据的知识,以帮助您更全面地了解这个主题。

本文目录一览:

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

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

注意:我也在以下AngularJS邮件列表中发布了此问题:https
://groups.google.com/forum/#!
topic/
angular/UC8_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''});});

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];  });

在我更改之后,它们如下所示:

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 data");                return data;            } else {                console.log("getting countries from server");                return countries();             }        }    };  });

CountryController:

$scope.countries = CountryService.getCountries(function(result){        console.log("i need a callback function here...");});

问题是我曾经能够使用$
resource.query()中的回调函数来预先选择默认选择,但是现在我将query()调用移到了CountryService内,我似乎丢失了什么。

解决此问题的最佳方法是什么?

感谢您的帮助,肖恩

答案1

小编典典

Ok..so看起来我通过将回调函数一直传递到resource.query()调用解决了问题。仍不确定这是否是最佳方法。

供参考,这是我所做的:

CountryController:

$scope.countries = CountryService.getCountries(function(){    //preselected default    $scope.selected.country = $scope.countries[0];  });

CountryService:

//Country Service. Will contain all relevant rest methods hereservices.factory(''CountryService'', function($resource) {    var countryService = {};    var data;    var resource = $resource(''http://localhost:port/restwrapper/country.json'', {port: '':8080''});    var countries = function(callback) {        data = resource.query(callback);        return data;    }    return {        getCountries: function(callback) {            if(data) {                console.log("returning cached data");                return data;            } else {                console.log("getting countries from server");                return countries(callback);             }        }    };  });

ajax – 在angular.js中的控制器之间共享变量

ajax – 在angular.js中的控制器之间共享变量

我是新的角度和我想知道如何我可以在角度控制器之间共享一个变量。我使用以下脚本 –

在Main.js中:

function MainCntl($scope) {
  ---code
}

function SearchCtrl($scope,$http) {
    $scope.url = 'http://10.0.0.13:9000/processAdHoc';
    $scope.errorM = "No results";     
    $scope.search = function() {

        $http.post($scope.url,{ "data" : $scope.keywords}).
        success(function(data,status) {
            $scope.status = status;
            $scope.data = data;
            $scope.result = data; 
            alert('yes');
        })
        .
        error(function(data,status) {
            $scope.data = data || "Request Failed";
            $scope.status = status;   
            alert('no');
            $scope.result = "Failed";
        });
    };
}

在Index.html中

<body ng-controller="MainCntl" >
---code
<div ng-controller="SearchCtrl">
     <form>
     <div>
          <label for="tags"></label>
          <a ng-click="search()"><input type="image" src="../../images/search1.png"https://www.jb51.cc/tag/Box/" target="_blank">Box_submit" /></a>
          <input ng-model="keywords" placeholder="Shadow Search" id="tags"/> 
     </div>
     </form>
</div>
---code
<p ng-model="result">
     {{result}}
</p>
</body>

一切工作良好与ajax我发送数据和接收响应,我的问题如下:

在SearchCtrl函数中,我有一个名为$ scope.result的变量,稍后在Index.html中引用。如果我插入包含该变量的HTML代码到SearchCtrl控制器,它工作正常,但如果它是在MainCtrl控制器,它不工作。如何在控制器之间共享此变量。

先谢谢

使用服务并将它注入到两个控制器,并将范围vars引用到服务变量。

例:

angular.module("yourAppName",[]).factory("myService",function(){

  return {sharedobject: {data: null } }

});

function MainCtrl($scope,myService) {
  $scope.myVar = myService.sharedobject;
}

function SearchCtrl($scope,$http,myService) {
  $scope.myVar = myService.sharedobject;
}

在你的模板做:

{{myVar.data}}

See an example使用Angular v1.1.5

将它放在内部对象中的原因是保留引用,如果保持它没有“sharedobject”,并更改该对象,您的绑定将指向旧的引用,并且不会在模板中显示任何内容。

angularjs – Angular docs:如何在控制器之间共享无状态/有状态代码?

angularjs – Angular docs:如何在控制器之间共享无状态/有状态代码?

正在阅读Angular.js’ Controller docs并偶然发现:

Sharing stateless or stateful code across Controllers — Use angular
services instead.

但这让我不确定.如何在控制器之间共享无状态/有状态代码?或者“代码”在这里意味着什么?一个模型?此外,据我所知,控制器不会互相引用.任何人都可以为我(其他人)解决问题吗?谢谢.

我认为他们所指的可能是“持久化”数据,在控制器之间或路由变化之间共享数据的方法之一.一种方法是将它放在rootScope中,另一种方法是使用服务.如果您定义这样的服务:
.factory("MyDataObject",function() {
    return {};
})

然后MyDataObject将是您调用它的任何对象,允许您将内容保存到其中,以便在控制器(或指令或其他服务等)之间共享数据,函数和状态.

你永远不会知道Angular文档,但我猜他们正在谈论的是:)

例如,请参阅此答案:Angularjs,passing scope between routes

angularjs – 使用服务以角度在多个控制器之间共享ajax数据

angularjs – 使用服务以角度在多个控制器之间共享ajax数据

嗨我有两个控制器

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这样的监听器

angularjs – 在不同模块中的指令和控制器之间共享数据

angularjs – 在不同模块中的指令和控制器之间共享数据

我已经和AngularJS玩了几天,想出了一些我还无法解决的问题.

每个联系人都可以有多个地址和电话号码.由于插入和编辑联系人在UI级别需要几乎相同的功能,因此我决定创建一个类似以下的指令来处理地址和电话:

地址:

(function () {
    var app = angular.module("AddressesEditorModule",[]);
    app.directive("addressesEditor",function () {
        return {
            restrict: "E",templateUrl: "/addressesEditorTemplate.html",controller: function ($scope) {
                this.addresses = [
                    // this will hold addresses.
                ];

                // ...
            }
        }
})();

电话:

(function () {
    var app = angular.module("PhonesEditorModule",[]);
    app.directive("phonesEditor",templateUrl: "/phonesEditorTemplate.html",controller: function ($scope) {
                this.phones = [
                    // this will hold phones.
                ];

                // ...
            }
        }
})();

我省略了在指令中声明的方法来处理地址和电话变量.

这两个指令在HTML中使用如下:

<div ng-app="ContactModule">
    <div ng-controller="InsertController as insertCtrlr">
        <!-- some other elements handling contact name goes here -->

        <addresses-editor></addresses-editor>
        <phones-editor></phones-editor>
    </div>
</div>

这项工作完全符合我的预期,正确记录电话和地址.

现在,我想要做的是检索指令内的电话和地址,并将它们发送到服务器,以便记录在数据库的联系人.

我知道如何执行AJAX,但我不知道如何在指令和InsertController之间交换数据(带有我想要的数据的变量是:来自addressesEditor指令的this.addresses和来自phonesEditor指令的this.phones).

我怎么能做到这一点?

解决方法

您可以将共享服务/工厂与要共享的数据一起使用.

为了说明如何完成,我使用服务创建了一些示例代码,以在控制器和指令之间共享数据:

app.factory('SharedService',function() {
  return {
    sharedobject: {
      value: ''
    }
  };
});

http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=preview

希望有所帮助

关于AngularJS:使用共享服务带有$ resource在控制器之间共享数据,但是如何定义回调函数?的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于ajax – 在angular.js中的控制器之间共享变量、angularjs – Angular docs:如何在控制器之间共享无状态/有状态代码?、angularjs – 使用服务以角度在多个控制器之间共享ajax数据、angularjs – 在不同模块中的指令和控制器之间共享数据等相关内容,可以在本站寻找。

本文标签: