3

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);
            });
...

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.