rst*_*ter 14 angularjs angularjs-service
我试图配置我的AngularJs的第一个花絮是一个微不足道的东西,但不幸的是,经过相当长的时间后,它没有成功.
我的前提:
用户从下拉列表中选择一个选项,并将相应的模板加载到选择下方的div中.我已经设置了服务,一个自定义指令(通过@Josh David Miller在这篇文章中关注ans ,以及一个控制器到位.服务中的ajax调用工作正常,除了我传递给服务器的params是硬编码的我希望这是用户选择的下拉列表中的"密钥".目前我没有将此代码传递给服务.
我的配置:
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);
}
});
}
};
})
Run Code Online (Sandbox Code Playgroud)
并且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>
Run Code Online (Sandbox Code Playgroud)
我需要$ http ajax调用中当前的硬编码值'b1'作为$ scope.breed.code中的值.
rol*_*and 18
您的ajax请求是异步的,而您的控制器的行为就像请求是同步的一样.
我假设get请求具有正确执行所需的一切.
首先将回调传递给您的服务(请注意fn的用法):
firstModule.factory( 'katTplLoadingService', function ($http) {
return {
fn: function(code, callback) { //note the callback argument
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}",
params:{code: code}}) //place your code argument here
.success(function (template, status, headers, config) {
callback(template); //pass the result to your callback
});
};
};
});
Run Code Online (Sandbox Code Playgroud)
在你的控制器中:
$scope.loadBreedData = function() {
katTplLoadingService.fn($scope.breed.code, function(tmpl) { //note the tmpl argument
$scope.template = tmpl;
});
}
Run Code Online (Sandbox Code Playgroud)
这样做,您的代码现在处理您的异步获取请求.
我没有测试它,但它一定是在做这个工作.
| 归档时间: |
|
| 查看次数: |
38304 次 |
| 最近记录: |