Wednesday, October 9, 2013

ng-blur in Angular JS


ng-blur is one of the directives provided by the angular framework which can trigger custom behaviour on blur. you can use it as an attribute in various html elements.
For example,

Hello world!

Let us see a simple example

Let this be my design page

If yoy observe the above example ,The user simply enters his or her name.On leaving the textbox ie on blur the user should get his username generated automatically in the next textbox.
ng-blur="myName()" is the attribute we have used in whch we raised an event which gets triggered on blur.

Now i handle the event in my javascript file, and the code here is,
if($scope.username===null || $scope.username==="")
$scope.model.username=$ + "someId";
//here "someId" can be a sequence of numbers
So when the user types his Name and moves to the next field his username is automatically generated,his name attached with some id.

ng-blur not working

This is one of the major problems complained by many fresh devolopers ,that my ng-blur not working.Yes this happens,especially because of the version which you are currently using.So check out in official website to know perfectly which vers ions support ng-blur and then proceed.


Evevthough we have support for ng-blur in latest versions,but if you got already started with older versions ,still you could manually get the functionality by adding the directive code manually to your application.>/br> Attach the following like this to your application:
app.directive('ngBlur', ['$parse', function($parse) {
  return function(scope, element, attr) {
    var fn = $parse(attr['ngBlur']);
    element.bind('blur', function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});

Now your application supports ng-blur directive and you can start using this as attribute like what we have done in the example explained above.

Hope this helps you and please feel free to suggest an comment.

No comments:

Post a Comment