将参数传递给AngularJs中的服务
发布时间:2020-12-17 07:44:02 所属栏目:安全 来源:网络整理
导读:我正在尝试配置我的第一个角度的AngularJs的一个微不足道的东西,但不幸的是,在相当长的时间后失败. 我的前提: 用户从下拉列表中选择一个选项,并将适当的模板加载到选择下面的div中.我已经设置了这个服务,一个自定义的指令(通过@Josh David Miller在这个post
我正在尝试配置我的第一个角度的AngularJs的一个微不足道的东西,但不幸的是,在相当长的时间后失败.
我的前提: 我的配置: var firstModule = angular.module('myNgApp',[]); // service that will request a server for a template firstModule.factory( 'katTplLoadingService',function ($http) { return function() { $http.get("${createLink(controller:'kats',action:'loadBreedInfo')}",{params:{'b1'}} ).success(function(template,status,headers,config){ return template }) }; }); firstModule.controller('KatController',function($scope,katTplLoadingService) { $scope.breed = {code:''} // here I am unsuccessfully trying to set the user selected code to a var in service,//var objService = new katTplLoadingService(); //objService.breedCode({code: $scope.breed.code}); $scope.loadBreedData = function(){ $scope.template = katTplLoadingService(); } }); firstModule.directive('showBreed',function ($compile) { return { scope: true,link: function (scope,element,attrs) { var el; attrs.$observe( 'template',function (tpl) { if (angular.isDefined(tpl)) { el = $compile(tpl)(scope); element.html(""); element.append(el); } }); } }; }) 和HTML设置 <form ng-controller="KatController"> <select name="catBreeds" from="${breedList}" ng-change="loadBreedData()" ng-model="breed.code" /> <div> <div show-breed template="{{template}}"></div> </div> </form> 我需要$http ajax调用中当前硬编码的值’b1’成为$scope.breed.code中的值.
您的ajax请求是异步的,而您的控制器的行为就像请求是否同步.
我认为获取请求具有执行正确的一切. 首先将回调传递给您的服务(注意fn的用法): firstModule.factory( 'katTplLoadingService',function ($http) { return { fn: function(code,callback) { //note the callback argument $http.get("${createLink(controller:'kats',params:{code: code}}) //place your code argument here .success(function (template,config) { callback(template); //pass the result to your callback }); }; }; }); 在你的控制器中: $scope.loadBreedData = function() { katTplLoadingService.fn($scope.breed.code,function(tmpl) { //note the tmpl argument $scope.template = tmpl; }); } 这样做你的代码正在处理你的异步获取请求. 我没有测试,但它一定是在做这件事. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |