Angular Directive:将'mouseover'事件绑定到元素

时间:2015-02-25 01:39:32

标签: javascript angularjs events bind directive

在我的控制器中,我有以下用户数组,将通过部分html模板中的迭代显示

控制器中的

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}
    ];

部分HTML代码:

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

myCustomer指令: 我希望在客户端发生鼠标悬停事件时增加客户的年龄。是否可以在指令中执行此操作?

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模板:

<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>

2 个答案:

答案 0 :(得分:4)

更多&#34; Angular&#34;做事方式是使用ng-mouseover

你可以把它放在&#34;部分html&#34;图

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

ng-mouseover在Angular上下文中表达了表达式。这可确保一切都在Angular上下文中,您无需担心手动触发摘要。

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

per @floriban

您也可以将其置于指令模板本身

<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>

答案 1 :(得分:1)

e.target是您已用鼠标移动的HTML元素。请改用真实用户信息:

element.bind('mouseover', function(e) {
   scope.customerInfo.age++;
});

另外,您可以使用内置ng-mouseover指令在HTML中执行所有操作。在views / directives / myCustomer.html中:

<div ng-mouseover="customerInfo.age++"> ... content of the template </div>

注意:您可能更喜欢ng-mouseenter不会在鼠标悬停的每个像素上触发事件,而只是在用鼠标进入区域时触发事件。