Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: How to pass a input value to a function?

I have an input and I need when pressing 'Enter' to call a function to reload the listed items. For that I am using

ng-keyup="$event.keyCode == 13 ? loadItems('a constant') : null"

that works quiet well when using a constant value at the loadItems call, but as soon as I want to pass the input value I get an error:

<input id="input-search" name="mysearch" ng-keyup="$event.keyCode == 13 ? loadItems({{mysearch}}) : null" placeholder="Search">
  <span id="input-search-clear" class="fa fa-times-circle"></span>
</input>

That is what I get

http://errors.angularjs.org/1.2.14/$parse/syntax?p0=mysearch&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=36&p3=%24event.keyCode%20%3D%3D%2013%20%3F%20loadItems(%7B%7Bmysearch%7D%7D)%20%3A%20null&p4=mysearch%7D%7D)%20%3A%20null
at Error (native)
at http://localhost:8080/vendor/angular-1.2.14/angular.min.js:6:450
at Ya.throwError (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:158:422)
at Ya.consume (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:159:394)
at Ya.object (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:167:45)
at Ya.primary (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:158:57)
at Ya.unary (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:164:273)
at Ya.multiplicative (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:164:6)
at Ya.additive (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:163:376)
at Ya.relational (http://localhost:8080/vendor/angular-1.2.14/angular.min.js:163:240) <input id="input-search" name="mysearch" ng-keyup="$event.keyCode == 13 ? loadItems({{mysearch}}) : null" placeholder="Search"> 
like image 804
jmhostalet Avatar asked Mar 23 '14 00:03

jmhostalet


1 Answers

You don't need the {{ }}. I assume you already have mysearch defined, but if not, you also need ng-model like this:

<input id="input-search" name="mysearch" ng-model="mysearch" ng-keyup="$event.keyCode == 13 ? loadItems(mysearch) : null" placeholder="Search">
    <span id="input-search-clear" class="fa fa-times-circle"></span>
</input>

Also, you should use a directive like ngEnter from this StackOverflow answer to make the code cleaner: https://stackoverflow.com/a/17364716/3450859

Then it would be:

<input id="input-search" name="mysearch" ng-model="mysearch" ng-enter="loadItems(mysearch)" placeholder="Search">
    <span id="input-search-clear" class="fa fa-times-circle"></span>
</input>
like image 54
Prerender.io Avatar answered Nov 10 '22 13:11

Prerender.io