2016-07-13 101 views
1

我有以下指令傳遞事件參數的自定義指令

.directive('uiBlur', function() { 
return function(scope, elem, attrs) { 
     elem.bind('blur', function() { 
     scope.$apply(attrs.uiBlur); 
    }); 
}; 

})

這是HTML

<input id="mainOdd1Id" type="number" ng-model="data.mainOdd1" placeholder="#1 Main Odd" onfocus="this.placeholder=''" min="0" step="any" ui-Blur="testfn('data.mainOdd1', $event, '#1 Main Odd');"> 

而且這是在控制器的功能

$scope.testfn = function(propertyName, $event, placeHolder){ 
    alert(propertyName); 
} 

我看到調試器$ event是未定義的...

這裏有什麼問題?

感謝

+0

試試這個,NG-點擊=「MYFUNC( 'data.mainOdd1',{$事件:$事件},」#1 Main Odd') –

回答

1

該代碼被打破接收到的事件在不止一個地方。

  1. Attrs總是字符串。所以你不能將它們傳遞給作用域。
  2. 您需要解析運行$ parse service的表達式。
  3. 您需要使用傳遞給事件偵聽器的事件參數。

這裏是工作示例:

angular 
 
    .module('app', []) 
 
    .directive('uiBlur', function($parse) { 
 
    return function(scope, elem, attrs) { 
 
     elem.bind('blur', function(event) { 
 
     scope.$apply(function() { 
 
      $parse(attrs.uiBlur)(scope, { 
 
      $event: event 
 
      }); 
 
     }); 
 
     }); 
 
    }; 
 
    }) 
 
    .controller('Example', function($scope) { 
 
    $scope.testfn = function(propertyName, $event) { 
 
     console.log(propertyName, $event); 
 
    }; 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script> 
 

 
<div ng-app="app" ng-controller="Example"> 
 
    <input type="text" placeholder="#1 Main Odd" ui-blur="testfn('data.mainOdd1', $event, '#1 Main Odd');"> 
 
</div>

+0

非常感謝您的回答。有幾件事,什麼是$ parse輸出?我看到您傳遞給函數(scope,$ event),get(propertyName,$ event),是否正確? –

+0

@ASFStudio checkout文檔$ parse https://docs.angularjs.org/api/ng/service/$parse這裏有一些例子,q請稍微解釋一下。 – sielakos

0

可以綁定uiBlur與指令

.directive('uiBlur', function() { 
return function(scope, elem, attrs) { 
     elem.bind('blur', function(evt) { 
     scope.$apply(attrs.uiBlur.bind(evt); 
    }); 
}; 

您可能還需要綁定的屬性,如data.mainOdd1和#1主奇

相關問題