Use a $formatter on a object typed ngModel value with angular 1.2 worked, but not with version 1.3

心已入冬 提交于 2019-12-05 17:31:41

In 1.3 you should be doing it like this (which will also work in 1.2):

.directive('myDir', function(){
    return {
        restrict :'A',
        require:'ngModel',
        link : function(scope, elt, attrs, modelCtrl){

            // conversion "view -> model"
            modelCtrl.$parsers.push( function(value){
                console.log('Value:', value);
                return {label:value, value:value};
            })

            // conversion "model -> view"
            modelCtrl.$formatters.push(function formatter(modelValue){
                console.log('modelValue:', modelValue);
                return modelValue.label;
            })
        }
    }
})

Because if you unshift your $formatter in 1.3, then you will get the stringified value of the model, if you want to have access to the non stringified value of the model, you will have to put your $formatter at the end (push).

I know that this contradicts this comment of Igor Minar.

The breaking change is that the viewValue passed into formatters will be a toString version of the formatted modelValue. So if any custom formatters execute after the default formatter, they'll see the string version of the value. If any formatter needs access to the value before it was stringified, the formatter should be registered via $formatters.unshift(customFormatter).

But things changed after that comment.

Example

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