Angular ng-keyup not working when calling a function
24,132
Solution 1
ng-keyup
works perfectly fine for me. See this fiddle for an example: http://jsfiddle.net/r74a5m25/
Code:
<div ng-controller="MyCtrl">
Hello:
<input ng-model="testModel" ng-keyup="search()"/>
</div>
function MyCtrl($scope, $log) {
$scope.search = function() {
alert('test');
};
}
Make sure you have an up to date version of angular in order to use ng-keyup
. It looks like it has been available since version 1.0.8
.
Solution 2
Try to $watch
your variable
JS
$scope.$watch('search.input',function(){
$scope.doSearch('watched!'); //call your function here
});
HTML
<input type="text" placeholder="ابحث" ng-model="search.input">
Related videos on Youtube
Author by
Elliott Coe
Updated on June 03, 2020Comments
-
Elliott Coe almost 4 years
I've got this code:
<input type="text" ng-model="keywords" ng-keyup="search()">
It doesn't call the search function where as, if I do ng-click="search()" it does work. Why is this?
-
Blackhole over 9 yearsCan't say without more information. What version of AngularJS are you using?
-
Elliott Coe over 9 yearsJust thinking, surely this should work if ng-click works?
-
Blackhole over 9 yearsAbsolutely. The problem isn't here, I think. Can you make a fiddle reproducing the problem?
-
Elliott Coe over 9 yearsCheck out my site: elliottcoe.com/search/index.html
-
-
Elliott Coe over 9 yearsHere's my site: elliottcoe.com/search/index.html I've taken the ng-click out of the submit button and put ng-keyup in the text input.
-
Matt Way over 9 yearsYou are using a very old version of angular. Update it and your code should work.
-
Elliott Coe over 9 yearsI updated to a new version but now ng-bind-html-unsafe doesn't work, how do I get it to work with out having to make ridiculous changes to my controller?
-
Matt Way over 9 yearsIt looks like this question has been answered then. You now should ask a completely new one.
-
A. Khaled almost 7 yearsThe value will change when key-up, down or press. This is better for searching for my opinion.
-
Vladimir almost 7 yearsI believe so, but note you may have problems using $watch when dealing with a ng-model appended to a input with attributes, max, min, step, maxlength. Once you do not follow these attributes (e.g. Input: 20 when the is max="10") the ng-model ends up undefined, and the $watch will stop being triggered, but that's just my experience.
-
A. Khaled almost 7 yearsThanks for your notice. I never tried $watch with strict on inputs.