Angular Directive: bind ‘mouseover’ event to an element Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Angular Directive: bind ‘mouseover’ event to an element without wasting too much if your time.

The question is published on by Tutorial Guruji team.

In my controller, I have the following array of users, which will be displayed by iteration in the partial html template

in controller:

vm.users = [
      {"username": "johnDoe", "address": "Saltlake City, UT", "age": 34},
      {"username": "janeDoe", "address": "Denver, CO", "age": 33},
      {"username": "patrickDoe", "address": "San Francisco, CA", "age": 35}
    ];

partial html code:

<div ng-repeat="user in mapView.users">
<my-customer info="user"></my-customer></div>

myCustomer directive: I wish to increment the customer’s age when the mouseover event happens on the customer. Is it possible to do this in the directive?

angular
    .module('angularApp')
    .directive('myCustomer', function() {

  return {
    restrict: 'E',
    link: function(scope, element) {
      element.bind('mouseover', function(e) {
        e.target.age++; // this is not working, need help here!
        console.log(e.target, 'mouseover');
      });
    },
    scope: {
      customerInfo: '=info'
    },

    templateUrl: 'views/directives/myCustomer.html'
  };

}); //myCustomer

myCustomer template:

<span>
  <label class="label-success">Username: {{customerInfo.username}}</label>
</span>
  <span>
    <label class="label-default">{{customerInfo.address}}</label>
  </span>
  <span>
    <label class="label-danger">{{customerInfo.age}}</label>
  </span>

Answer

The more “Angular” way of doing things would be to use ng-mouseover

You could put it in the “partial html” view

<my-customer 
    info="user"
    ng-mouseover="user.age = user.age + 1;"></my-customer>

ng-mouseover evals the expression within the Angular context. This ensures everything is within the Angular context and you never have to worry about triggering digests manually.

https://docs.angularjs.org/api/ng/directive/ngMouseover

per @floriban

You could also put it within the directive template itself

<div ng-mouseover="customerInfo.age = customerInfo.age + 1;">
  <span>
    <label class="label-success">Username: {{customerInfo.username}}</label>
  </span>
  <span>
    <label class="label-default">{{customerInfo.address}}</label>
  </span>
  <span>
    <label class="label-danger">{{customerInfo.age}}</label>
  </span>
</div>
We are here to answer your question about Angular Directive: bind ‘mouseover’ event to an element - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji