Skip to content Skip to sidebar Skip to footer

How To Trigger 'change' On A Hidden Field Bound To A Scope Variable With Angularjs Without Jquery?

I have a complex control (button clicks, dropdowns, etc) that builds a string. So every button click/dropdown selection calls a scope function that in turn updates a scope variable

Solution 1:

Something you can do is to use a $watch within your directive so it is reusable. See the answer here

Essentially, within your link function you can $watch the attrs.ngModel, which catches any changes. Your link function would change to something like this:

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

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

Edit: You might want to check for newVal and oldVal being 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
            }
        });
    }

Post a Comment for "How To Trigger 'change' On A Hidden Field Bound To A Scope Variable With Angularjs Without Jquery?"