AngularJS $ watch is called every time you press a text key

I have a webpage where I create a form from dynamic json data received from the server. I recently developed it using KnockoutJS. After creating the form, I also have a requirement to update the form by running an ajax request from the server, every time the value in the form has been changed. Here is the fiddle. You see that the change event occurs only when blurring (and not when you press a key). For example, if the text field has a value of 15 and the user presses the backspace and then enters 5 again, this means 2 keystrokes, but the value has not been changed. So far so good.

Problem 1 Now I am converting code to AngularJS. I am trying to catch a change event on $ watch of scope. But it looks like the clock starts every time a key is pressed, although after a few key presses the value does not change. Below is the fiddle about how I am trying. However, this problem has only text type input fields.

Problem 2 I create a radio group manually, for example. if the json data is changed, we will also need to update the html. How can I do this in some dynamic way. I was able to do this with KnockoutJS.

Problem 3 Why does ng-hide not work?

+4
source share
2 answers

The fix for problem 1 was to introduce a directive for the blur event, the following is the code for 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 could not understand the solution to problem 2, so I stopped using the radio inputs.

+5
source

Instead of using blur, you can just use a timeout. Essentially, this calls your function when the user stops typing in X milliseconds, and not every time a key is pressed.

See this answer for a similar question, in which there is an example of code that does the job: fooobar.com/questions/217906 / ...

+1
source

Source: https://habr.com/ru/post/1485049/


All Articles