2013-03-11 56 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