How to manually rerun formatter chain in angularjs directive with ngModel?

前端 未结 1 1865
你的背包
你的背包 2021-01-19 22:07

Angular.js ngModel has the ability to declare a chain of parsers and formatters. Some more details can be found at the great answer to \'How to do two-way filtering in angul

相关标签:
1条回答
  • 2021-01-19 22:25

    currently there is no direct api to call the internal formatter chain. there is a github feature request for this. as work-around you just can copy the internal code:

    function runFormatters(ctrl){
        // this function is a copy of the internal formatter running code.
        // https://github.com/angular/angular.js/issues/3407#issue-17469647
    
        var modelValue = ctrl.$modelValue;
    
        var formatters = ctrl.$formatters;
        var idx = formatters.length;
    
        var viewValue = modelValue;
    
        while (idx--) {
            viewValue = formatters[idx](viewValue);
        }
    
        if (ctrl.$viewValue !== viewValue) {
            ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
            ctrl.$render();
    
            ctrl.$$runValidators(modelValue, viewValue, angular.noop);
        }
    
    }
    

    this Plunker demonstrates the usage in combination with a watch for additional parameters:

    // deepwatch all listed attributes
    scope.$watch(
        function(){
            return [scope.extraThingToWatchFor, scope.someOther];
        },
        function() {
            console.log("\t runformatters()");
            runFormatters();
        },
        true
    );
    

    this is a second Plunker to demonstrate the deepwatch on ngModel

    // deepwatch ngModel
    scope.$watch(
        function(){
            return ngModelCtrl.$modelValue;
        },
        function(newData) {
            runFormatters(ngModelCtrl);
        },
        true
    );
    
    0 讨论(0)
提交回复
热议问题