2013-03-11 57 views
3

我创建on-blur指令为从输入字段如何通过一个功能的指令里面AngularJS

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

myObject的看起来模糊了用户,如:

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

这是怎么了我的指令目前看起来像:

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

     } 
    } 
}); 

我该怎么做exe可爱的功能doSomething({{myObject}})当模糊事件触发?

我试着做这样的事情已经无法正常工作:

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

回答

2

内部连接功能,您可以拨打:scope.doSomething()。要评估表达式,您可以执行:scope.$eval(expression),要访问范围对象,只需使用:scope.myObject

当然,这只适用于不能单独工作的指令。

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> 

Working plunker