我刚刚提出了一个指令,根据来自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"}]}
模板:
指示:
App .directive("inputSelect" , function() { var Template = ''; 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(); }])
但仍未定义:/.
我怎样才能将direclty资源(包含我可以用来推迟select的加载的承诺)传递给指令?
ANGULARJS 1.2的解决方案:
指示:
App .directive("inputSelect" , function() { var Template = ''; 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