Question

I have a webpage where i am building a form from dynamic json data received from server. I have developed it with KnockoutJS, a while ago. After building the form, i also have a requirement to update the form by doing an ajax request from the server, everytime a value in the form has been changed. Here is the fiddle You see that, change event only occurs on blur (not on keypress). For example, if a text field has a value 15, and user presses backspace and then enters 5 again, that means 2 keypresses but value has not been changed. So far so good.

Problem 1 Now i am converting the code to AngularJS. I am trying to catch the change event by $watch of scope. But, it seems like watch is run everytime a keypress is happened, even though after few keypresses value is not changed. Here is the fiddle of how i am attempting. This problem is however with only text type input fields.

Problem 2 I am creating radiogroup in a manual way, e.g. if the json data is changed then we will also have to update the html as well. How can i do that in a kind of dynamic way. I was able to do that with KnockoutJS.

Problem 3 Why ng-hide is not working?

Was it helpful?

Solution

Fix for the problem 1 was to introduce a directive for blur event, following is the code of my directive:

angular.module('app', []).directive('ngModelOnblur', function () {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, elm, attr, ngModelCtrl) {
        if (attr.type === 'radio' || attr.type === 'checkbox') return;

        elm.unbind('input').unbind('keydown').unbind('change');
        elm.bind('blur', function () {
            scope.$apply(function () {
                ngModelCtrl.$setViewValue(elm.val());
            });
        });
    }
};

});

you can see the working fiddle here http://jsfiddle.net/akeelrehman/GNJtn/1/

I couldn't figure out the solution for problem 2, so i have stopped using radio inputs.

OTHER TIPS

Instead of using blur, you could just use a timeout. In effect this calls your function when the user has stopped typing for X milliseconds, instead of on every keypress.

See this reply to a similar question, which has example code that does the job: https://stackoverflow.com/a/15723514/1034002

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top