我有一个选择标签(用于国家选择),我想使用指令预选选项:
<select class="countryselect" required ng-model="cust.country"></select>
我的指令就像
return { restrict : "C",link: function postLink(scope,iElement,iAttrs) { var countries = [ ["AND","AD - Andorra","AD"],["UAE","AE - Vereinigte Arabische Emirate","AE"] ... //loop array and generate opt elements iElement.context.appendChild(opt); } }
我可以使用附加选项填充选择,但是ng模型绑定不起作用.即使cust.country具有值(例如“UAE”),则不选择该选项.
如何使选择显示cust.country的值?如果认为我在这里有一些时间问题.
解决方法
您可以使用Angular JS中的指令:
标记:
<div ng-controller="MainCtrl"> <select ng-model="country" ng-options="c.name for c in countries"></select> {{country}} </div>
脚本:
app.controller('MainCtrl',function($scope) { $scope.countries = [ {name:'Vereinigte Arabische Emirate',value:'AE'},{name:'Andorra',value:'AD'},]; $scope.country = $scope.countries[1]; });
检查选择:Angular Select的文档
编辑方向
指示:
app.directive('sel',function () { return { template: '<select ng-model="selectedValue" ng-options="c.name for c in countries"></select>',restrict: 'E',scope: { selectedValue: '=' },link: function (scope,elem,attrs) { scope.countries = [{ name: 'Vereinigte Arabische Emirate',value: 'AE' },{ name: 'Andorra',value: 'AD' },]; scope.selectedValue = scope.countries[1]; } }; });
主控制器
app.controller('MainCtrl',function($scope) { $scope.country={}; })
标记:
<div ng-controller="MainCtrl"> <sel selected-value="country"></sel> {{country}} </div>
工作实例:EXAMPLE