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">
Share:
24,132

Related videos on Youtube

Elliott Coe
Author by

Elliott Coe

Updated on June 03, 2020

Comments

  • Elliott Coe
    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
      Blackhole over 9 years
      Can't say without more information. What version of AngularJS are you using?
    • Elliott Coe
      Elliott Coe over 9 years
      Just thinking, surely this should work if ng-click works?
    • Blackhole
      Blackhole over 9 years
      Absolutely. The problem isn't here, I think. Can you make a fiddle reproducing the problem?
    • Elliott Coe
      Elliott Coe over 9 years
  • Elliott Coe
    Elliott Coe over 9 years
    Here'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
    Matt Way over 9 years
    You are using a very old version of angular. Update it and your code should work.
  • Elliott Coe
    Elliott Coe over 9 years
    I 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
    Matt Way over 9 years
    It looks like this question has been answered then. You now should ask a completely new one.
  • A. Khaled
    A. Khaled almost 7 years
    The value will change when key-up, down or press. This is better for searching for my opinion.
  • Vladimir
    Vladimir almost 7 years
    I 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
    A. Khaled almost 7 years
    Thanks for your notice. I never tried $watch with strict on inputs.