Dejell
Dejell

Reputation: 14317

angular.js on-keyup doesn't work

I would like to make a javascript alert/call a function onkeyup.

But it doesn't work. see Plunker

Simply:

<input ng-keyup="alert('hi')">

What's wrong?

Upvotes: 1

Views: 1383

Answers (2)

Narek Mamikonyan
Narek Mamikonyan

Reputation: 4611

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

Instead use services like $window and $location in functions called from expressions. Such services provide mockable access to globals.

that means you should write function alert in your controller , or inject $window service and reference from it

angular.module('test',[]).controller('testCtrl',function($scope){
        $scope.alert = function(text){
          alert(text)
        }

 })

here is updated example

from docs

Upvotes: 3

gkalpak
gkalpak

Reputation: 48212

The ngKeyup exprssion will be evaluated in the context of the current $scope, so everything you refer to needs to be declared on the $scope.

E.g.:

.controller('someCtrl', function ($scope, $window) {
    $scope.alert = $window.alert.bind($window);
    // Or
    // $scope.alert = function (msg) { $window.alert(msg); }
});

See, also, this short demo.

Upvotes: 3

Related Questions