将参数传递给AngularJs中的服务

前端之家收集整理的这篇文章主要介绍了将参数传递给AngularJs中的服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试配置我的第一个角度的AngularJs的一个微不足道的东西,但不幸的是,在相当长的时间后失败.

我的前提:
用户从下拉列表中选择一个选项,并将适当的模板加载到选择下面的div中.我已经设置了这个服务,一个自定义的指令(通过@Josh David Miller在这个post上跟随ans,并且有一个控制器.在服务中的ajax调用正常工作,只不过我传给服务器的参数是硬编码的我希望这是用户选择的下拉菜单中的“关键”,目前我没有将此代码传递给服务.

我的配置:

  1. var firstModule = angular.module('myNgApp',[]);
  2.  
  3. // service that will request a server for a template
  4. firstModule.factory( 'katTplLoadingService',function ($http) {
  5.  
  6. return function() {
  7.  
  8.  
  9. $http.get("${createLink(controller:'kats',action:'loadBreedInfo')}",{params:{'b1'}}
  10. ).success(function(template,status,headers,config){
  11. return template
  12.  
  13. })
  14. };
  15. });
  16.  
  17.  
  18. firstModule.controller('KatController',function($scope,katTplLoadingService) {
  19. $scope.breed = {code:''}
  20.  
  21. // here I am unsuccessfully trying to set the user selected code to a var in service,//var objService = new katTplLoadingService();
  22. //objService.breedCode({code: $scope.breed.code});
  23.  
  24.  
  25. $scope.loadBreedData = function(){
  26. $scope.template = katTplLoadingService();
  27. }
  28. });
  29.  
  30.  
  31.  
  32. firstModule.directive('showBreed',function ($compile) {
  33. return {
  34. scope: true,link: function (scope,element,attrs) {
  35. var el;
  36. attrs.$observe( 'template',function (tpl) {
  37.  
  38. if (angular.isDefined(tpl)) {
  39.  
  40. el = $compile(tpl)(scope);
  41. element.html("");
  42. element.append(el);
  43. }
  44. });
  45. }
  46. };
  47. })

和HTML设置

  1. <form ng-controller="KatController">
  2.  
  3. <select name="catBreeds" from="${breedList}" ng-change="loadBreedData()"
  4. ng-model="breed.code" />
  5.  
  6. <div>
  7.  
  8. <div show-breed template="{{template}}"></div>
  9.  
  10. </div>
  11.  
  12. </form>

我需要$http ajax调用中当前硬编码的值’b1’成为$scope.breed.code中的值.

您的ajax请求是异步的,而您的控制器的行为就像请求是否同步.

我认为获取请求具有执行正确的一切.

首先将回调传递给您的服务(注意fn的用法):

  1. firstModule.factory( 'katTplLoadingService',function ($http) {
  2. return {
  3. fn: function(code,callback) { //note the callback argument
  4. $http.get("${createLink(controller:'kats',params:{code: code}}) //place your code argument here
  5. .success(function (template,config) {
  6. callback(template); //pass the result to your callback
  7. });
  8. };
  9. };
  10. });

在你的控制器中:

  1. $scope.loadBreedData = function() {
  2. katTplLoadingService.fn($scope.breed.code,function(tmpl) { //note the tmpl argument
  3. $scope.template = tmpl;
  4. });
  5. }

这样做你的代码正在处理你的异步获取请求.

我没有测试,但它一定是在做这件事.

猜你在找的Angularjs相关文章