如何使用 ngModel 在 angularjs 指令中手动重新运行格式化程序链? [英] How to manually rerun formatter chain in angularjs directive with ngModel?

查看:25
本文介绍了如何使用 ngModel 在 angularjs 指令中手动重新运行格式化程序链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular.js ngModel 能够声明一个 解析器格式化程序.更多详细信息可以在 如何在 angular.js 中进行双向过滤?"的精彩回答中找到?

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 angular.js?'

现在格式化程序链只有在 ngModel 更新时才会运行.因此,如果您有第二个影响 viewValue 的输入参数(在其中一个格式化程序中使用),则不会触发视图的更新.就我发现 ngModel 仅使用一个简单的 $watch 而言类似 - 所以如果您的模型是一个集合/对象,它不会在子元素发生更改时触发.

now the formatter chain only will be run if the ngModel will update. so if you have a second input-parameter that affects the viewValue (is used in one of the formatters) this will not trigger an update of the View. similar as far as i found ngModel only uses a simple $watch - so if your model is a collection/object it will not trigger if sub-elements are changed.

实现 ngModel 深度监视的最佳方法是什么 -
还是监视应该重新运行格式化程序链的附加参数?

还有其他类似的问题:
Angularjs:如何在某些设置时重新运行"$formatters改变了吗?

推荐答案

目前没有直接调用内部格式化链的api.对此有一个 github 功能请求.作为解决方法,您只需复制内部代码:

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 演示了结合观察附加参数的用法:>

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
);

这是第二个Plunker,用于在ngModel 上演示deepwatch

this is a second Plunker to demonstrate the deepwatch on ngModel

// deepwatch ngModel
scope.$watch(
    function(){
        return ngModelCtrl.$modelValue;
    },
    function(newData) {
        runFormatters(ngModelCtrl);
    },
    true
);

这篇关于如何使用 ngModel 在 angularjs 指令中手动重新运行格式化程序链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆