A.S.F Studio A.S.F Studio - 4 months ago 8
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() {
scope.$apply(attrs.uiBlur);
});
};


})

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){
alert(propertyName);
}


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

What is wrong here?

Thanks

Answer

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:

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>