ufk
ufk

Reputation: 32094

ng-keyup doesn't execute the expression

I'm using angular 1.5.0-beta2

I'm trying to create a simple keyUp detect on a text input.

code for the div:

<div ng-controller="IndexController">
 <div class="jumbotron">
  <h1>Hello and Welcome to MyAlcoholist</h1>
  <p>A growing database of cocktails and drinks for your reach</p>
  <hr/>
  <p>
   <span class="glyphicon glyphicon-search" aria-hidden="true">
   Search for Cocktail
         </span></p>
  <p>
   <input type="text" id="cocktail_search_input" ng-model="test" ng-keyup="cocktailSearchInput($event.keyCode)" />
   <span id="cocktail-search-icon-span"></span>
  <a href="javascript:cocktailInfo()" class="btn btn-primary">
         Cocktail Info
        <span class="glyphicon glyphicon-chevron-right"></span>
        </a>
 </div>
<div class="container">
 <div class="row">
  <div id="latest-drinks-div" class="col-md-3"></div>
  <div id="latest-cocktails-div" class="col-md-3">
    <p>blah blah blah blah blah blah</p>
       </div>
  <div class="col-md-3">
    <p>blah blah blah blah blah blah</p>
      </div>
  <div class="col-md-3">
    <p>blah blah blah blah blah blah</p>
      </div>
 </div>
   </div>
</div>

my app.js

(function(){
var app = angular.module('myalcoholist',['ngRoute']);
app.controller('IndexController', function () {
    this.cocktailSearchInput = function(code) {
        alert(code);
    }
});
})()

i don't see any errors and the cocktailSearchInput function is not being executed.

any ideas why?

Upvotes: 0

Views: 380

Answers (1)

lux
lux

Reputation: 8436

It looks as though cocktailSearchInput is bound to the controller itself (by way of this), but not the $scope of the controller.

Try injecting $scope into the controller, and then hanging your function off of it. By doing so, the function is now available on $scope and therefore accessible from the DOM:

app.controller('IndexController', function ($scope) {
    $scope.cocktailSearchInput = function(code) {
        alert(code);
    }
});

Here's a plunker with your code, you'll note we get the alert on keyUp: http://plnkr.co/edit/L3zmHk1jugbX6jrzx4i8?p=info

Upvotes: 1

Related Questions