[英]Angular js : How to make make ajax call for directives to create options
我為表單控件創建了指令。 有一些控件將具有來自ajax [API]調用的選項。
我被困在這里,如何通過指令進行ajax調用。
function selectControlDir()
{
return {
transclude: true,
restrict: 'E',
scope: {
data: '=data'
},
template: "<div ng-transclude></div><label>{{data._text}} </label><select type='text' name='{{data._attributeName}}' id='{{data._attributeName}}' >\n\
<option ng-repeat='ans in data._answerOptions'>{{ans._promptText}}</option></select>"
,
link: function (scope, element, attrs)
{
//console.log("scope.data.QuestionData", scope.data.QuestionData);
}
};
}
請插入完整代碼http://plnkr.co/edit/Op1QDwUBECAosPUC7r3N?p=preview
在這里,我想對Year進行api調用(頁面加載)。 按年份更改Make的更新選項。
為此,您最好做的是在year
元素上使用ng-change
事件指令,並在控制器中使用一個數組來保存當年發生的所有make:
var app = angular.module('yourApp', []);
app.controller('yourController', ['$scope', '$http',
function($scope, $http) {
$scope.o = {
makes: [{make:'Make1'}, {make:'Make2'}], // <---just for demo
getMake: function(year) {
$http.post(url, {
year: year // <----pass the year to backend as year like : { year:1990 }
})
.then(function success(response) {
$scope.o.makes = response.data; // <---put actual data here
},
function error(e) {
console.error(e);
});
}
};
}
]);
<div ng-app='yourApp' ng-controller='yourController'>
<select ng-model='year' ng-change='o.getMake(year)'>
<option>1990</option>
<option>1991</option>
</select>
<select ng-model='make' ng-options='make as make.make for make in o.makes track by make.make'>
<option>Make...</option>
</select>
</div>
您應該通過有角度的服務獲得選項。 角度服務將發送AJAX調用並返回結果(如果發生故障,甚至返回一些默認數據)。
怎么做? 這是一個例子:
var app = angular.module('app',[]);
//Service
app.factory('myService', function(){
function getOption() {
return 'getOption';
}
return {
getOption: getOption
}
});
app.directive('myDirective', ['myService',function(myService){
return {
template: '<h1>{{name}}</h1>'
link: function (scope, element, attrs) {
scope.name = myService.getOption();
}
}
}]);
使用可以使用$ http進行ajax調用。 您需要注入它才能使用它。 更好的解決方案是將服務呼叫移至工廠/服務。
function selectControlDir($http)
{
return {
transclude: true,
restrict: 'E',
scope: {
data: '=data'
},
template: "<div ng-transclude></div><label>{{data._text}} </label
> ><select type='text' name='{{data._attributeName}}' id='{{data._attributeName}}' >\n\ <option ng-repeat='ans in
> data._answerOptions'>{{ans._promptText}}</option></select>"
,
link: function (scope, element, attrs)
{
// $http.post(url, options); => make your call here
//console.log("scope.data.QuestionData", scope.data.QuestionData);
}
};
}
最好的方法是創建服務或工廠並將其注入您的指令中 。
app.service("serviceName", ["$http", function($http) {
return {
getData: function(configObject) {
// $http.get(..., post... etc
}
}
}]);
您可以在鏈接或控制器語句中使用它。
selectControlDir(serviceName) {
return{
...
link: function() {
selectControlDir.getData({ url: ..., getParam1: 123})
}
... or ...
controller: function() {
selectControlDir.getData({ url: ..., getParam1: 123})
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.