我有一个选择标记(用于国家/地区选择),我想使用指令预先填充选项:
<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-model绑定不起作用。即使cust.country具有值(例如“UAE”),也不会选择该选项。
如何让select显示cust.country的值?如果我认为这里有一些时间问题。
答案 0 :(得分:13)
你可以使用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
答案 1 :(得分:0)
您需要将选项添加到ngModelController,以便工作。例如。像这样:
return {
restrict : 'C',
require: ['select', 'ngModel'],
link: function(scope, element, attrs, controllers) {
var countries = [['A', 'text text']];
countries.forEach(option => {
const optionElement = angular.element('<option/>')
.attr('value', option[0])
.text(option[1]);
element.append(optionElement);
controllers[0].addOption(option.value, optionElement);
});
}
};