在AngularJS中跟随鼠标的弹出对话框 [英] Popup dialog that follow the mouse in AngularJS

查看:180
本文介绍了在AngularJS中跟随鼠标的弹出对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 1.0.6和jQuery,我需要创建一个将跟随鼠标(更改位置)的提示.到目前为止,我所要做的是显示/隐藏:

I'm using Angular 1.0.6 and jQuery and I need to create a hint that will follow the mouse (change position). What I have so far is the 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>

如何根据mousemove事件更改弹出窗口的x和y位置?我当时以为我可以有这样的东西:

How should I change x and y position of the popup depend on mousemove event? I was thinking that I could have something like this:

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

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

But don't know how to create directive like this.

推荐答案

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

I came up with this utility that can be used as a service (it require $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]);
                        }
                    }
                }
            }
        }
    }
}

此函数会将对象(字符串)中的值解析为作用域值,返回的对象将允许基于其他对象更改这些值.可以在这样的指令中使用它:

This function will parse values from object (string) as scope values, and returned object will allow to change those values based on other object. It can be used in directive like this:

{
    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
                });
            });
        });
    }
};

这篇关于在AngularJS中跟随鼠标的弹出对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆