A.S.F Studio
A.S.F Studio

Reputation: 43

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

Upvotes: 2

Views: 661

Answers (2)

sielakos
sielakos

Reputation: 2404

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>

Upvotes: 2

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

You can bind uiBlur with event received in the directive

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

You might also need to bind properties like data.mainOdd1 and #1 Main Odd

Upvotes: 0

Related Questions