Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular's ng-blur on input field not working

Ok, so I'm pretty sure I'm missing something obvious, but I'm not seeing it.

I created a fiddle that I would have thought would throw an alert message when the input box loses focus, but it's not working and I don't know why.

I was expecting an alert message when the user performs the following steps:

  1. click the input box
  2. type something
  3. click somewhere outside of the input box

but these steps do not show an alert message.

Surely, someone knows what I'm doing wrong...?

Here's the code (same as the fiddle):

<div ng-app>
  <div ng-controller="MyCtrl">  
    <form name="myForm">
      <input type="text" ng-model="todoText" size="30"
         name="myInput" ng-blur="validate(myForm)">
    </form>
  </div>
</div>

function MyCtrl($scope) {
  $scope.validate = function(form) {
    alert('blur!');
  };
}
like image 422
sfletche Avatar asked Feb 10 '16 23:02

sfletche


People also ask

How does ng blur work?

The ng-blur directive tells AngularJS what to do when an HTML element loses focus. The ng-blur directive from AngularJS will not override the element's original onblur event, both the ng-blur expression and the original onblur event will be executed.

What does blur mean in Angular?

A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope.


1 Answers

It could be your version of angular. Your fiddle is using 1.0.x I updated you to 1.4.x and its working fine:

<div ng-app='myApp'>
  <div ng-controller="MyCtrl">  
  {{santity}}
    <form name="myForm">
      <input type="text" ng-model="todoText" size="30"
             name="myInput" ng-blur="validate(myForm)">
    </form>
  </div>
</div>

Javascript

angular.module('myApp', []);
angular.module('myApp').controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
 $scope.santity = 'Hello';
 $scope.validate = function(form) {
  alert('blur!');
 };
}

http://jsfiddle.net/ncapito/LurjLvz7/6/

like image 92
Nix Avatar answered Oct 04 '22 19:10

Nix