我有一個select
我呈現這樣的:角:NG-模型作爲數
<select
ng-model="otherDoc.sub_category"
ng-options="key as value for (key, value) in vm.otherDocs"
>
</select>
otherDoc.sub_category
然而一個number
,選擇的值轉換爲字符串。所以他們不匹配。
我該如何告訴角度匹配模型的內容而不是類型?
我有一個select
我呈現這樣的:角:NG-模型作爲數
<select
ng-model="otherDoc.sub_category"
ng-options="key as value for (key, value) in vm.otherDocs"
>
</select>
otherDoc.sub_category
然而一個number
,選擇的值轉換爲字符串。所以他們不匹配。
我該如何告訴角度匹配模型的內容而不是類型?
訣竅是使用ngModel。$解析器和ngModel。$格式化
如果我理解你,你要來了從選擇返回值它擊中的模型(otherDoc之前轉換回一個數字。 sub_category)。
我想一個指令添加到您的選擇,像這樣
(的HTML)
<select
ng-model="otherDoc.sub_category
ng-options="key as value for (key, value) in vm.otherDocs"
formatter-directive>
</select>
(JavaScript的)
angular.module('someModuleName').directive('formatterDirective', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$formatters.push(function(val) {
return parseInt(val, 10);
});
}
};
});
模型中的值會被解析成當它從視圖返回時,以10爲整數。
另外這是一篇關於格式器和解析器的好文章-https://alexperry.io/angularjs/2014/12/10/parsers-and-formatters-angular.html –
這在[select'的文檔中提到](https://docs.angularjs.org/api/ng/directive/select#binding-select-to-a-non-string-value-via- ngmodel-parsing-formatting) –