2016-07-13 35 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主奇

相关问题