双向绑定这个特性有时让人又爱又恨
假设控制器
function($scope){
$scope.options = [{name:”alex”,id:232,…},{…},{…}…];
$scope.myModel = {name:”alex”,id:232};
}
<select ng-model=”myModel.id”>
<option value=””>—请选择—</option>
<option ng-repeat=”opt in options” value=”{{opt.id}}” >
{{opt.name}}
</option>
</select>
ok,这段看起来很寻常的代码会出现问题
inspect一下
?number:45?
多次调试发现不是程序写得有问题
这个是angular中select的一个缺陷
以下是官方说法
To bind the model to a non-string value, you can use one of the following strategies:
- the
ngOptions
directive (select
) - the
ngValue
directive, which allows arbitrary expressions to be option values (Example) - model $parsers / $formatters to convert the string value (Example)
然而我尝试了ngOptions时依然无效
最终解决方案:
app.directive(‘convertToNumber’, function () {
return {
require: ‘ngModel’,
link: function (scope, element, attrs, ngModel) {
ngModel.$parsers.push(function (val) {
return val != null ? parseInt(val, 10) : null;
});
ngModel.$formatters.push(function (val) {
return val != null ? ” + val : null;
});
}
};
});