将事件参数传递给自定义指令

时间:2016-07-13 12:21:20

标签: javascript angularjs ionic-framework

我有以下指令

.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未定义...

这里有什么问题?

由于

2 个答案:

答案 0 :(得分:1)

此代码在多个地方被破解。

  1. Attrs总是字符串。因此,您无法将它们传递给范围。$ apply需要函数。
  2. 您需要使用$ parse service解析运行它的表达式。
  3. 您需要使用传递给事件侦听器的事件参数。
  4. 以下是工作示例:

    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>

答案 1 :(得分:0)

您可以将uiBlur与指令

中收到的事件绑定
.directive('uiBlur', function() {
return function( scope, elem, attrs ) {
        elem.bind('blur', function(evt) {
        scope.$apply(attrs.uiBlur.bind(evt);
    });
};

您可能还需要绑定data.mainOdd1和#1 Main Odd

等属性