Alon
Alon

Reputation: 7758

How to pass a function inside a directive in AngularJS

I have created on-blur directive for user that blurs out from the input field

<input type="text" on-blur="doSomething({{myObject}})">

myObject looks like:

myObject = {a : foo, b : bar ... }

this is how my directive currently looks like:

    myModule.directive('onBlur',function(){
    return {
        restrict: 'A',
        link: function(scope,element,attrs) {
            element.bind('blur',function(){
                console.log('blurrred');
            });

        }
    }
});

How do I execute the function doSomething({{myObject}}) when the blur event is triggered?

I've tried doing something like this that has failed to work:

...
            element.bind('blur',function(){
                console.log('blurrred');
                doSomething(object);
            });
...

Upvotes: 3

Views: 3715

Answers (2)

Stewie
Stewie

Reputation: 60416

You ng-blur is missing scope.$apply. It has no reference to your callback function, and you callback function needs to be defined at current scope:

JS:

var app = angular.module('plunker', []);
app.controller('AppController',
    [
      '$scope',
      function($scope) {
        $scope.myObject = {a: 'foo', b: 'bar'};

        $scope.doSomething = function(item){
          console.log(item);
        };
      }
    ]
  );

app.directive('ngBlur', function() {
  return function( scope, elem, attrs ) {
    elem.bind('blur', function() {
      scope.$apply(attrs.ngBlur);
    });
  };
});

HTML:

<div ng-controller="AppController">
  <input ng-blur="doSomething(myObject)" />  
</div>

Working plunker.

Upvotes: 2

ŁukaszBachman
ŁukaszBachman

Reputation: 33735

Inside linking function you can call: scope.doSomething(). To evaluate expression you could do: scope.$eval(expression), to get access to scope objects simply use: scope.myObject.

Of course this is only true for directives not working in isolation.

Upvotes: 2

Related Questions