如何在鼠标悬停时更新repeat中元素的样式

How to update the style of an element inside a repeat on mouseover

本文关键字:repeat 元素 样式 更新 鼠标 悬停      更新时间:2023-09-26

我正试图在ng鼠标悬停器上更新ng repeat中元素的ng样式。我试过几个主意,但似乎都想不通。以下是我的代码背后的基本思想:

视图:

<div ng-repeat="data in days | orderBy:'timestamp'"
     ng-style="seriesStyle(data)"
     ng-mouseover="examineSeries(data)"></div>

控制器:

$scope.examineSeries = function (data) {
    $scope.frame = data; // used for other things
    // want to update the width of the mouseover'd element's seriesStyle
    // here to something higher than 1%
}
$scope.seriesStyle = function (data) {
    return {
        'background-color': data.color,
        'width': '1%'
    }
}

请注意,由于其他依赖关系,我不能只在每个元素上放一个类并使用:hover

我认为处理这件事的正确方法是创建一个指令,该指令将检查鼠标悬停时的数据,并在需要时更新样式。看看这个jsfiddle,它展示了如何做到

HTML:

<div ng-app="myapp">
  <div ng-controller="AppCtrl as ctrl">
    <div ng-repeat="day in ctrl.days" ng-style="ctrl.seriesStyle(day)" update-on-mouse-over>{{day}}</div>
  </div>
</div>

Javascript:

var myapp = angular.module('myapp', []);
myapp.controller('AppCtrl', function () {
  this.days = [
    {name:'Sun', color:'red'},
    {name:'Mon', color:'blue'},
    {name:'Tue', color:'orange'}
  ];
  this.seriesStyle = function (day) {
    return {
      'background-color': day.color
    };
  };
});
myapp.directive('updateOnMouseOver', function() {
return {
    link: function(scope, element, attrs) {
        element.on('mouseover', function() {
            element.css('background-color', 'green');
        });
    }
  };
});