在AngularJS中跟随鼠标的弹出对话框

Popup dialog that follow the mouse in AngularJS

本文关键字:对话框 鼠标 AngularJS 跟随      更新时间:2023-09-26

我使用Angular 1.0.6和jQuery,我需要创建一个提示,将跟随鼠标(改变位置)。到目前为止我只有show/hide:

<div ng-repeat="item in items">
    <span ng-mouseover="item.show_description=true" ng-mouseleave="item.show_description=false">
       {{item.text}}
    </span>
    <div class="description-popup" ng-show="item.description && item.show_description">
       {{item.description}}
    </div>
</div>

我应该如何改变x和y位置的弹出依赖于mousemove事件?我想我可以这样写:

<div pointer="{x: item.x, y: item.y}">Hello</div>
<div class="popup" style="left: {{item.x}}; top: {{item: y}}">
  Popup
</div>

但是不知道如何创建这样的指令

我想出了这个可以作为服务使用的实用程序(它需要$parse):

function objectParser(expr) {
    var strip = expr.replace(/'s*'{'s*|'s*'}'s*/g, '');
    var pairs = strip.split(/'s*,'s*/);
    if (pairs.length) {
        var getters = {};
        var tmp;
        for (var i=pairs.length; i--;) {
            tmp = pairs[i].split(/'s*:'s*/);
            if (tmp.length != 2) {
                throw new Error(expr + " is Invalid Object");
            }
            getters[tmp[0]] = $parse(tmp[1]);
        }
        return {
            assign: function(context, object) {
                for (var key in object) {
                    if (object.hasOwnProperty(key)) {
                        if (getters[key]) {
                            getters[key].assign(context, object[key]);
                        }
                    }
                }
            }
        }
    }
}

这个函数将从object (string)中解析值作为范围值,并且返回的对象将允许基于其他对象更改这些值。它可以在这样的指令中使用:

{
    restrict: 'A',
    link: function(scope, element, attrs) {
        var expr = objectParser(attrs.pointer);
        element.mousemove(function(e) {
            var offest = element.offset();
            scope.$apply(function() {
                expr.assign(scope, {
                    x: e.pageX - offest.left,
                    y: e.pageY - offest.top
                });
            });
        });
    }
};