ng-mouseenter在AngularJs Factory中无法正常工作

时间:2015-11-19 17:25:53

标签: angularjs tooltip mouseevent onmouseover angularjs-factory

我正在尝试在我的工厂内实现工具提示类型功能,但是在工厂内部调用ng-mouseenter和ng-mouseleave事件时遇到了问题。 请指导如何进行。

代码: HTML:

<DOCTYPE html>
<html ng-app="demoApp">
    <head>
        <title>Mouseevent - Second</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
        <style>
        .red{
            background-color: red;
        }
        .show{
            background: lightgray;
            border: 1px solid black;
            position: absolute;
            z-index: 98;
        }
        </style>
    </head>
    <body ng-controller="demoController">
        <div ng-bind-html="fromFactory"></div>
</body>
</html>

App.js

var app = angular.module('demoApp',[])
app.controller('demoController',function($scope,$sce,hoverFactory){
$scope.fromFactory = hoverFactory.demo();
$scope.onMouseEnter = function(evt){
  $scope.hovered = true;
  $scope.mouse = {
               'left': evt.pageX + 10  + 'px' ,
               'top': evt.pageY + 10 + 'px'
  }
};
$scope.onMouseLeave = function(){
    $scope.hovered = false;
  }
});

app.factory('hoverFactory',function($sce){
  return{
    demo:function(){
    var template = '<div  ng-class="{red: hover}" ng-mouseenter="onMouseEnter($event)"'+ 
       'ng-mouseleave="onMouseLeave()" > "Hover mouse on me to make tooltip move! "</div>' +
       '<div class="show" ng-show="hovered" ng-style="mouse" ng-init= "hover=false">movable tooltip</div>';

      var result = $sce.trustAsHtml(template);
      return result;
    }
  }
});

请引导人们,我被困了

1 个答案:

答案 0 :(得分:0)

您应该使用属性tooltips-target的指令。在那里,您可以访问元素的范围并应用您需要的任何jquery工具提示:

<div  tooltips-target >lorem</div>

并创建指令

app.directive('tooltipsTarget', function() {
  return {
    restrict: 'E',
    scope: {},
    link: function (scope, element) {
      $(element).myTooltips();
    }
  };
});

这是一个JSFiddle链接:

JsFiddle