Javascript 如何在AngularJS中的指令内传递函数

Javascript 如何在AngularJS中的指令内传递函数,javascript,html,angularjs,Javascript,Html,Angularjs,我已经为从输入字段中模糊出来的用户创建了关于模糊的指令 <input type="text" on-blur="doSomething({{myObject}})"> 这就是我的指令当前的样子: myObject = {a : foo, b : bar ... } myModule.directive('onBlur',function(){ return { restrict: 'A', link: function(scope,

我已经为从输入字段中模糊出来的用户创建了关于模糊的
指令

<input type="text" on-blur="doSomething({{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');
            });

        }
    }
});
触发模糊事件时,如何执行函数doSomething({{myObject}})

我尝试过这样做,但失败了:

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

在链接函数中,您可以调用:
scope.doSomething()
。要计算表达式,您可以执行:
scope.$eval(expression)
,要访问范围对象,只需使用:
scope.myObject


当然,这仅适用于不独立工作的指令。

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

JS:

HTML:


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);
    });
  };
});
<div ng-controller="AppController">
  <input ng-blur="doSomething(myObject)" />  
</div>