簡體   English   中英

Angular Directive:將'mouseover'事件綁定到元素

[英]Angular Directive: bind 'mouseover' event to an element

在我的控制器中,我有以下用戶數組,將在部分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>

更“角度”的做事方式是使用ng-mouseover

你可以把它放在“部分html”視圖中

<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

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

e.target是您已經鼠標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不會在鼠標懸停的每個像素上觸發事件,而只是在用鼠標進入區域時觸發事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM