How to trigger ng-change in directive test in AngularJS

后端 未结 5 1051
情歌与酒
情歌与酒 2021-01-01 15:13

I have the following AngularJS directive that creates an input element. Input has ng-change attribute that runs doIt() function. In my

5条回答
  •  执念已碎
    2021-01-01 16:00

    I googled "angular directive trigger ng-change" and this StackOverflow question was the closest I got to anything useful, so I'll answer "How to trigger ng-change in a directive", since others are bound to land on this page, and I don't know how else to provide this information.

    Inside the link function on the directive, this will trigger the ng-change function on your element:

    element.controller('ngModel').$viewChangeListeners[0]();
    

    element.trigger("change") and element.trigger("input") did not work for me, neither did anything else I could find online.

    As an example, triggering the ng-change on blur:

    wpModule.directive('triggerChangeOnBlur', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                element.on('blur', function () {
                    element.controller('ngModel').$viewChangeListeners[0]();
                });
            }
        };
    }]);
    

    I'm sorry that this is not directly answering OP's question. I will be more than happy to take some sound advice on where and how to share this information.

提交回复
热议问题