Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update view in $parser

Tags:

angularjs

I have the following custom validator directive:

app.directive('validator', ['storeService', function (storeService) {
    return {
        require: '^ngModel',
        link: function ($scope, $element, $attrs, $ctrl) {

            $ctrl.$parsers.unshift(function (viewValue) {

                var store = storeService.find(viewValue);

                if (store == undefined) {
                    $ctrl.$setValidity('store', false);
                    return undefined;
                } else {
                    $ctrl.$setValidity('store', true);

                    return store;
                }
            });
        }
    };
}]);

The call to 'storeService.find(viewValue);' checks to see if the viewValue exists. When doing the lookup it lower cases the viewValue and each store in the set of stores. If it matches a store it returns the store from the service with the correct casing.

So for example, user types in 'london' and the service returns 'London'.

How do I update the view with the value from the service?

like image 410
Ian Warburton Avatar asked May 15 '26 07:05

Ian Warburton


1 Answers

Since you put required:'ˆngModel' in your directive, the $ctrl in your link function will be ngModelController. You have to call ngController's method $setViewValue inside a scope.$apply function and than call ngController's $render method , like so:

else {
    $ctrl.$setValidity('store', true);    
    // sets viewValue
    scope.$apply(function(){
        $ctrl.$setViewValue($VALUE_YOU_WISH); 
    });
// renders the input with the new viewValue
$ctrl.$render()
// returns store as parameter for next parser in the pipeline
return store;
}

Remember that the returned value of the function you're unshifting to $parsers is what will be passed as parameter for the next parser in ngModelControllers $parsers pipeline and not the value that will be rendered in the view.

like image 185
rodrigo.botti Avatar answered May 16 '26 22:05

rodrigo.botti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!