我有一个像这样的角度指令:
'use strict';
angular.module('countrySelect', [])
.directive('countrySelect', ['$parse', function($parse) {
var countries = [
{ code: "af", name: "Afghanistan" },
{ code: "ax", name: "Åland Islands" },
{ code: "al", name: "Albania" },
{ code: "dz", name: "Algeria" },
];
return {
template: '<select ng-options="c.code as c.name for c in countries">',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
if (!!attrs.ngModel) {
var assignCountry = $parse(attrs.ngModel);
elem.bind('change', function(e) {
assignCountry(elem.val());
});
scope.$watch(attrs.ngModel, function(country) {
elem.val(country);
});
}
}
}
}]);
模板中的选择字段如下:
<div country-select ng-model="citizenship"></div>
我可以选择一个选项,模型会根据需要使用国家/地区代码进行更新,但国家/地区名称不会出现在选择字段中,除非我再次选择它。
换句话说,过程就是
如何在选择时让选择字段显示国家/地区名称?
答案 0 :(得分:2)
由于您使用的是replace: true
原始ng-model="citizenship"
,最终会以select元素结束,因此您无需处理选择更改事件以更新ngModel
,它是已绑定选择框。所以你的指令看起来应该是这样的:
angular.module('countrySelect', [])
.directive('countrySelect', [function() {
var countries = [
{ code: "af", name: "Afghanistan" },
{ code: "ax", name: "Åland Islands" },
{ code: "al", name: "Albania" },
{ code: "dz", name: "Algeria" },
];
return {
template: '<select ng-options="c.code as c.name for c in countries"></select>',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
}
}
}]);
答案 1 :(得分:0)
您可能希望使用GET / POST
来强制更新&#34;风景。
http://jimhoskins.com/2012/12/17/angularjs-and-apply.html