问题
For example,
If I have a scope value:
$scope.bankInfo = '808,CityBank';
And an input field:
<input name="bank_number" ng-model="bankInfo " />
I don't know what is the proper way to bind my input field only to digit part (that is 808). Should I use custom directive?
回答1:
I found that custom directive is a good approach to intercept binding. Let declare a directive like this:
module.directive('banknumber', function () {
return {
require: 'ngModel',
link: function ($scope, $element, $attrs, modelCtrl) {
modelCtrl.$formatters.push(function (inputValue) {
var modelValue = modelCtrl.$modelValue;
var bkno = (modelValue == null) ? '' : modelValue.split(',')[0];
return bkno;
});
modelCtrl.$parsers.push(function (inputValue) {
var modelValue = modelCtrl.$modelValue;
var bankName = (modelValue == null) ? '' : modelValue.split(',')[1];
return modelCtrl.$viewValue + ',' + bankName;
});
}
};
});
apply to input and it's done:
<input name="bank_number" ng-model="bankInfo" banknumber/>
来源:https://stackoverflow.com/questions/19969740/how-to-intercept-value-binding-by-ng-model-directive