我刚刚提出了一个指令,该指令根据来自API调用($resource)的列表加载下拉框。
控制器:
App.controller(
'TestCtrl', [
'$scope', 'countriesFactory',
function($scope, countriesFactory){
/* Call API */
countriesFactory().then(function(data){
$scope.countryList = data;
});
}])
API调用返回:
{"country":[{"code":"ABW","label":"Aruba"},{"code":"AFG","label":"Afghanistan"},{"code":"AGO","label":"Angola"}]}
模板:
<input-select model-ref-list="countryList"></input-select>
指令:
App
.directive("inputSelect"
, function() {
var Template =
'<select ng-options="item.label for item in modelRefList" required></select>';
return {
restrict: 'EA',
template: Template,
scope: {
modelRefList: '='
},
link: function(scope){
console.log(scope.modelRefList);
}
};
}
);
首先:我简化了整个问题,所以在这种情况下,该指令看起来完全过头了,但最终不是:D。
问题:我的console.log总是未定义。
我做了一些研究,意识到我需要兑现承诺,等待我的国家名单看起来真的符合指令。因此,我尝试修改我的控制器,不使用API调用promise的结果,而是直接使用资源本身:
新控制器:
App.controller(
'TestCtrl', [
'$scope', 'countriesFactory',
function($scope, countriesFactory){
/* Call API */
$scope.countryList = resourceAPICall();
}])
但仍未定义:/。
我如何将资源(包含我可以用来推迟select加载的promise)直接传递给指令?
ANGULARJS 1.2的解决方案:
指令:
App
.directive("inputSelect"
, function() {
var Template =
'<select ng-options="item.label for item in modelRefList" required></select>';
return {
restrict: 'EA',
template: Template,
scope: {
modelRefList: '='
},
link: function(scope){
scope.modelRefList.$promise.then(function(data){
console.log(data);
}
};
}
);
要将API调用结果传递给指令,需要传递其资源,并在指令本身中使用其promise。
感谢大家的帮助。
在这里,我们通过使用带有$q
的包装器来模拟异步调用工厂。
- 我们将
modelReflist
更改为modelRefList
- 将
ng-model="item"
添加到模板
HTML
<div ng-controller="TestCtrl">
<input-select model-ref-list="countryList"></input-select>
</div>
JS
var App = angular.module('myModule', ['ngResource']);
App.controller(
'TestCtrl', [
'$scope', 'countriesFactory',
function ($scope, countriesFactory) {
/* Call API */
countriesFactory.resourceAPICall().then(function (data) {
$scope.countryList = data.country;
console.log($scope.countryList);
});
}])
App.$inject = ['$scope', 'countriesFactory'];
App.directive("inputSelect", function () {
var Template = '<select ng-model="item" ng-options="item.label as item.label for item in modelRefList" required></select>';
return {
restrict: 'EA',
template: Template,
scope: {
modelRefList: '='
},
link: function (scope) {
console.log(scope.countryList);
}
};
});
App.factory('countriesFactory', ['$resource', '$q', function ($resource, $q) {
var data = {
"country": [{
"code": "ABW",
"label": "Aruba"
}, {
"code": "AFG",
"label": "Afghanistan"
}, {
"code": "AGO",
"label": "Angola"
}]
};
var factory = {
resourceAPICall: function () {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
演示Fiddle
modelReflist
需要在指令作用域中使用完全骆驼式大小写。modelRefList
。