Angular指令mouseenter/mouseleave正在工作,但在mouseleave之后不会设置为初始状态

Angular Directive mouseenter/mouseleave working but not setting to initial state after mouseleave

本文关键字:mouseleave 之后 设置 初始状态 但在 工作 mouseenter 指令 Angular      更新时间:2023-09-26

我有一个指示,显示一个模板上的学生信息列表,然后在鼠标输入上显示其他学生信息。我希望能够回到mouselleave的初始状态

尝试了所有的资源,但运气不佳。

html -这是我注入指令的地方

<div ng-repeat="student in studentPortfolio">
<portfolio-view student="student"></portfolio-view>
</div>

html指令模板

<div class="outer-box">
  <img src="{{student.picture}}" alt="{{student.name.first}} {{student.name.last}}" style="width: 200px; height: 200px">
  Name: {{student.name.first}} {{student.name.last}}
  <br>Bio: {{student.Bio}}
  <br>
  Skills:
<div ng-repeat="skill in student.skills">
{{skill.title}}
  </div>
  <br>
</div>

指令

app.directive('portfolioView', function() {
  return {
    restrict: 'E',
    scope: {
      student: "="
    },
    templateUrl: '/html-templates/hoverPortfolio.html',
    link: function(scope, elem, attrs) {
      //gets the first project and shows it
      var project = scope.student.projects;
      var firstProject = project[0];
      var fp_name = firstProject.name;
      var fp_type = firstProject.projectType;
      var fp_description = firstProject.description;
      //gets the second project and shows it
      var secondProject = project[1];
      var sp_name = secondProject.name;
      var sp_type = secondProject.projectType;
      var sp_description = secondProject.description;
      //the template that shows the second project
      var newHtml =
        '<div class="projects outer-box"><div class="firstproject"> Project Name: ' +
        fp_name + '<br>Type: ' + fp_type + '<br>Description: ' +
        fp_description +
        '</div><br><div class="secondproject"> Project Name: ' +
        sp_name + '<br>Type: ' + sp_type + '<br>Description: ' +
        sp_description +
        '</div> </div>';
      elem.on('mouseenter', function() {
        elem.html(
          newHtml
        )
      });
      elem.on('mouseleave', function() {
      //return to intial state
      });
    }
  }
});

我没有你的数据,但是ng-show的事情是有效的,就像在这个小提琴。

这里有一个更简单的变体。如果你的模板包含了你想要显示或隐藏的部分,并在其中添加了一个ng-show变量,你的指令可以相当简单:

return {
    restrict: 'EAC',
    replace: true,
    template: '<div><div ng-show="show">show</div><div ng-show="!show">hide</div></div>',
    link: function (scope, element, attrs, controller) {
        scope.show = true;
        element.on('mouseenter', function () {
            scope.$apply(function () {
                scope.show = false;
            });
        });
        element.on('mouseleave', function () {
            scope.$apply(function () {
                scope.show = true;
            });
        });
    }
};