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

2 回答 2

2

您可以在链接函数内部调用:scope.doSomething(). 要评估表达式,您可以这样做:scope.$eval(expression),要访问范围对象,只需使用:scope.myObject

当然,这只适用于非独立工作的指令。

于 2013-03-11T12:57:40.977 回答
2

您的 ng-blur 缺少范围。$apply。它没有引用您的回调函数,并且您的回调函数需要在当前范围内定义:

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>

工作笨拙

于 2013-03-11T13:01:16.953 回答