How to intercept value binding by ng-model directive

↘锁芯ラ 提交于 2020-01-23 02:18:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!