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