A.S.F Studio A.S.F Studio - 1 year ago 52
AngularJS Question

Passing the event argument to a custom directive

I have the following directive

.directive('uiBlur', function() {
return function( scope, elem, attrs ) {
elem.bind('blur', function() {


This is the 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');">

And this is the function in the controller

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

I see in the debugger that $event is undefined...

What is wrong here?


Answer Source

This code is broken in more than one place.

  1. Attrs are always string. So you cannot pass them to scope.$apply which expects function.
  2. You need to parse expression runing it with $parse service.
  3. You need to use event argument passed to event listener.

Here is working example:

  .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');">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download