How to trigger a "change" on a hidden field associated with a scope variable using AngularJs without JQuery?

I have a complex control (buttons, dropdowns, etc.) that build a string. Therefore, each selection of the button / dropdown call calls the scope function, which in turn updates the scope variable that contains my result.

I bind this scope variable to a hidden field in the UI:

<input type="hidden" ng-model="MyComplexString" custom-validation ng-value="MyComplexString" />

      

However, when the controller function updates MyComplexString, the custom check is not triggered.

I tried to change the input type to text, and indeed, MyComplexString is updated, however the custom validation still fails.

If I type in the textbox, the custom validation fires as expected.

Research shows that AngularJs listens for "input" events fired on DOM elements, but the controller function does not fire these events on inputs associated with scope variables after the scope variables have changed. So I need to do it manually.

Hope this makes sense. Any ideas would be appreciated.

Thank!

EDIT = Adding a check directive implementation (the implementation only checks if something starts with a "comma".

  .directive("customValidation", function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, ele, attrs, ctrl) {
            ctrl.$parsers.unshift(function(value) {
                var valid = false;
                if (value) {
                    // test and set the validity after update.
                    valid = value.charAt(0) == ',';
                    ctrl.$setValidity('customValFlag', valid);
                }
                return valid ? value : undefined;
            });
        }
    };
})

      

0


source to share


1 answer


Something you can do is use $watch

in your directive so that it is reused. See the answer here

Essentially, within your link function, you can $watch

attrs.ngModel

that catches any changes. Your function link

will change to something like this:

link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (newVal) {
                //Do custom validation here
            });
        }

      



See the working JSFiddle I forked here with two simple inputs and a hidden input using a directive that writes every change to the console

Edit: You might want to check that newVal and oldVal are equal to ignore the initialization call, which would look like this:

link: function (scope, element, attrs) {
        scope.$watch(attrs.ngModel, function (newVal, oldVal) {
            if(newVal !== oldVal) {
                //Do custom validation here
            }
        });
    }

      

0


source







All Articles