javascript - 在嵌套指令中,为什么我的子指令获取父指令的属性?

标签 javascript jquery angularjs d3.js

我正在使用 AngularJS+D3 创建交互式绘图工具。我对两者都不熟悉。我有一个包含框架的 framecontainer 指令。每个帧都是一个包含矩形和拖动 handle 的 svg 组。 Framecontainer 处理所有交互,包括添加新框架。每个帧可以包含更多帧。在 Framecontainer 指令的链接函数中,我编译了一个新框架并将其附加以添加新框架。现在,当我第一次使用 $compile 添加框架时,它会按预期添加框架。但是,当我拖动新添加的框架时,它似乎从父 DOM 元素获取其宽度和高度等属性。拖动函数采用父 DOM 元素的值。为什么会这样?

这是拖动功能:

var dragmove=function(d) {
                    if (scope.moveable==="true") {
                        console.log("COMES HERE TOO!");
                         d.x = Math.max(0, Math.min(w - width, d3.event.x));
                        d.y = Math.max(0, Math.min(h - height, d3.event.y));
                        d3.select(dragrect[0].parentNode).attr("transform","translate("+ d.x+","+ d.y+")");
                        translatex= d.x;
                        translatey= d.y;

                    }
                }    

moveable是通过读取属性在链接函数的开头设置的。在这个 dragmove 函数之外,值是它们应该的值。但是,在此函数内部,值似乎是父 DOM 元素的值。因此,scope.moveable 为 false,即使我将其设置为 true 并且在函数外部该值为 true。此外,框架指令需要 Framecontainer 指令并使用其 Controller 。

这是我的框架指令:

app.directive('frames',function($compile){
return{
    restrict:'E',
    priority:20,
    scope:{

    },
    replace:true,
    require:'^^framecontainer',
    template:"<g><rect id='{{surfaceID}}' class='drawarea' ng-Dblclick='popDialog()' fill-opacity='1' ng-attr-x='{{x}}' ng-attr-y='{{y}}' ng-attr-height='{{rectheight}}' ng-attr-width='{{rectwidth}}' stroke-width='3' cursor='move' stroke='{{strokecolor}}' ng-attr-fill={{rectfill}} ></rect>"
    + "<rect ng-attr-height='{{handlerheightr}}' class='dragr' opacity='0' ng-attr-x='{{handlerxr}}' ng-attr-y='{{handleryr}}' ng-attr-width='{{handlerwidthr}}' cursor='ew-resize'  fill='#773326' ></rect>"
    + "<rect ng-attr-height='{{handlerheightl}}' class='dragl' opacity='0' ng-attr-x='{{handlerxl}}' ng-attr-y='{{handleryl}}' ng-attr-width='{{handlerwidthl}}' cursor='ew-resize'  fill='#773326'></rect>"
    + "<rect ng-attr-height='{{handlerheightt}}' class='dragt' opacity='0' ng-attr-x='{{handlerxt}}' ng-attr-y='{{handleryt}}' ng-attr-width='{{handlerwidtht}}' cursor='ns-resize'  fill='#773326'></rect>"
    + "<rect ng-attr-height='{{handlerheightb}}' class='dragb' opacity='0' ng-attr-x='{{handlerxb}}' ng-attr-y='{{handleryb}}' ng-attr-width='{{handlerwidthb}}' cursor='ns-resize'  fill='#773326'></rect>"
    +"</g>",

    compile:function(s,e) {
        return {
            post: function postLink(scope, element, attr, controller) {
                var dragbarw = 10;
                scope.surfaceID=attr.id;
                scope.rectheight = attr.height;
                scope.rectwidth = attr.width;
                scope.strokecolor = attr.stroke;
                scope.rectfill = attr.fill;
                scope.x = attr.x;
                scope.y = attr.y;
                scope.handlerheightr = attr.height;

                scope.handlerwidthr=dragbarw;
                scope.handlerheightl = scope.rectheight;

                scope.handlerwidthl=dragbarw;
                scope.handlerheightt=dragbarw;
                scope.handlerheightb=dragbarw;
                scope.handlerwidtht=scope.rectwidth;
                scope.handlerwidthb=scope.rectwidth;

                scope.moveable=attr.mv;

                var w = 800;
                var h = 500;
                var width = scope.rectwidth;
                var height=scope.rectheight;
                var translatex,translatey;


                var dragrect = d3.select(element[0]).selectAll('.drawarea').attr("width","300");
                var entireContents=d3.select(element[0]).select('*');
                d3.select(element[0]).data([{x:0, y: 0}]);
                var dragbarleft=d3.select(element[0]).select(".dragl");
                var dragbartop=d3.select(element[0]).select(".dragt");
                var dragbarright=d3.select(element[0]).select(".dragr");
                var dragbarbottom=d3.select(element[0]).select(".dragb");

                // Selector and deselector
                var select = function () {
                    controller.addToSelection('#'+d3.select(this).attr("id"));
                    //controller.addToSelection(this);
                    d3.select(this).attr('stroke-dasharray', '5 5')
                        .on('click', deselect);

                };
                var deselect = function () {
                    controller.popFromSelection('#'+d3.select(this).attr("id"));
                    d3.select(this).attr('stroke-dasharray', '')
                        .on('click', select);
                };

                d3.select(element[0]).select('.drawarea').on('click', select);
                function rdragresize(d) {

                    var dragx = Math.max(d.x + (dragbarw / 2), Math.min(w, d.x + width + d3.event.dx));
                    width = dragx - d.x;
                    dragbarright.attr("x", function (d) {
                        return dragx;
                    });
                    dragrect.attr("width", width);
                    dragbarright.attr("x", dragx);
                    dragbartop
                        .attr("width", width - dragbarw)
                    dragbarbottom
                        .attr("width", width - dragbarw)
                }
                function ldragresize(d) {
                    var oldx = d.x;
                    //Max x on the right is x + width - dragbarw
                    //Max x on the left is 0 - (dragbarw/2)
                    d.x = Math.max(0, Math.min(d.x + width - (dragbarw / 2), d3.event.x));
                    width = width + (oldx - d.x);
                    dragbarleft
                        .attr("x", function(d) { return d.x - (dragbarw / 2)-translatex; });
                    dragrect
                        .attr("x", function(d) { return d.x-translatex; })
                        .attr("width", width);
                    dragbartop
                        .attr("x", function(d) { return d.x + (dragbarw/2)-translatex; })
                        .attr("width", width - dragbarw)
                    dragbarbottom
                        .attr("x", function(d) { return d.x + (dragbarw/2)-translatex; })
                        .attr("width", width - dragbarw)

                }
                function tdragresize(d){
                    var oldy = d.y;
                    d.y = Math.max(0, Math.min(d.y + height - (dragbarw / 2), d3.event.y));
                    height = height + (oldy - d.y);
                    dragbartop
                        .attr("y", function(d) { return d.y - (dragbarw / 2)-translatey; });

                    dragrect
                        .attr("y", function(d) { return d.y-translatey; })
                        .attr("height", height);

                    dragbarleft
                        .attr("y", function(d) { return d.y + (dragbarw/2)-translatey; })
                        .attr("height", height - dragbarw);
                    dragbarright
                        .attr("y", function(d) { return d.y + (dragbarw/2)-translatey; })
                        .attr("height", height - dragbarw);
                }
                var bdragresize=function(d){

                    var dragy = Math.max(d.y + (dragbarw/2), Math.min(h, d.y + height + d3.event.dy));

                    //recalculate width
                    height = dragy - d.y;

                    //move the right drag handle
                    dragbarbottom
                        .attr("y", function(d) { return dragy - (dragbarw/2) });

                    //resize the drag rectangle
                    //as we are only resizing from the right, the x coordinate does not need to change
                    dragrect
                        .attr("height", height);
                    dragbarleft
                        .attr("height", height - dragbarw);
                    dragbarright
                        .attr("height", height - dragbarw);
                }

                var dragmove=function(d) {
                    if (scope.moveable==="true") {
                        console.log("COMES HERE TOO!");
                         d.x = Math.max(0, Math.min(w - width, d3.event.x));
                        d.y = Math.max(0, Math.min(h - height, d3.event.y));
                        d3.select(dragrect[0].parentNode).attr("transform","translate("+ d.x+","+ d.y+")");
                        translatex= d.x;
                        translatey= d.y;

                    }
                }

                scope.popDialog=function()
                {


                    var newText=angular.element('<editabletext x="'+(scope.x+scope.rectwidth/2-scope.rectwidth/10)+'" y="'+scope.y+scope.rectheight/5+'" height="'+scope.rectheight/5+'" width="'+scope.rectwidth/5+'" text="Hello!!"></editabletext>');
                    element.append(newText);
                    $compile(newText)(scope);

                }

                function stopPropagation()
                {
                    d3.event.sourceEvent.stopPropagation();

                }


                var dragr = d3.behavior.drag().origin(Object).on("drag", rdragresize).on("dragstart",stopPropagation);
                var dragl=d3.behavior.drag().origin(Object).on("drag",ldragresize).on("dragstart",stopPropagation);
                var dragt=d3.behavior.drag().origin(Object).on("drag",tdragresize).on("dragstart",stopPropagation);
                var dragb=d3.behavior.drag().origin(Object).on("drag",bdragresize).on("dragstart",stopPropagation);
                var drag=d3.behavior.drag().origin(Object).on("drag",dragmove);

                console.log("ATTR-MV outside the drag function: "+attr.mv);

                d3.select(dragrect[0].parentNode).call(drag);
                dragbarleft.call(dragl);
                dragbarright.call(dragr);
                dragbartop.call(dragt);
                dragbarbottom.call(dragb);
            }
        }
    },

    controller:function($scope,$element)
    {
        this.getHeight=function()
        {
            return $scope.height;

        }

        this.getWidth=function()
        {
            return $scope.rectwidth;

        }

        this.getPosition=function()
        {

            return {x:scope.x,y:scop.y};

        }



        //$scope.$watch('fillFromParent',function(){ if ($scope.fillFromParent)$scope.rectfill=$scope.fillFromParent;});


    }
};});    

这是框架容器指令:

app.directive('framecontainer',function($compile){
return{
    restrict:'A',
    scope:{
        split:'=',
        mergeq:'=',
        fillparam:'@',
        perform:'='
    },
    priority:1,
    replace:true,
    transclude:false,
    template:'<svg><frames id ="maing" stroke="#bada55" x="0" y="0"  resize height="500" width="765" fill="#006600" mv="false"   dialog="poptextdialog()"> </frames></svg>',
    link:function(scope,element,attr)
    {
        scope.$watch('perform',function(){

            var newFrame;
            var curWidth;
            var curHeight;
            var curX,curY;
            var newFrame;
            var frameID=0;

            function getRectCor(x,y,width,height)
            {
                return {x:(parseFloat(x)-parseFloat(width)/2),y:(parseFloat(y)-parseFloat(height)/2)};
            }

            if (scope.perform) {
                switch (scope.perform.action) {
                    case 0:
                        angular.forEach(scope.selectionStack,function(value,i){

                            curWidth=100;
                            curHeight=100;

                            curX=10;
                            curY=10;


                            newFrame=angular.element('<frames data-mv="true" data-stroke="#bada55" data-x="'+curX+'" data-y="'+curY+'"   data-height="'+curHeight+'" data-width="'+curWidth+'" data-fill="#FFFFFF" id="elem'+frameID+'" ></frames>');
                            frameID=frameID+1;
                            console.log("value is "+value);

                            $(value).append(newFrame);
                            $compile(newFrame)(scope.$new(true));
                        });

                        break;

                }
            }
        });


        var firstFrame='<g frame id ="maing" stroke="#bada55" x="0" y="0"  resize height="500" width="765" fill="#006600" mv="true"   dialog="poptextdialog()"> </g>';
        element.append(firstFrame);
        $compile(firstFrame)(scope);

    },
    controller:function($scope,$element)
    {
        $scope.selectionStack=[];
        var indexSelectionStack;

        this.addToSelection=function(s){
            $scope.selectionStack.push(s);
            console.log($scope.selectionStack);
        };

        this.popFromSelection=function(s){
            var index=$scope.selectionStack.indexOf(s)
            if (index>-1){
                $scope.selectionStack.splice(index,1);
            }
        };

        $scope.$watch('fillparam',function(){
            angular.forEach($scope.selectionStack,function(value,index){
                d3.select(value).select("rect").attr("fill",$scope.fillparam);

            });

        });




    }
};});

对于庞大的帖子和 super 困惑的代码,我们深表歉意。我是 AngularJS 和 d3 的新手。

最佳答案

问题已解决。虽然这可能不是一个普遍的问题,但我认为它会帮助将来有人发布答案。这个错误非常微不足道。拖动事件冒泡到最顶层的父框架。因此,将拖动函数更改为调用以下解决了问题:

var drag=d3.behavior.drag().origin(Object).on("drag",dragmove).on("dragstart",stopPropagation);    

stopPropagation 函数防止拖动事件在 DOM 中冒泡。谢谢大家给我指出正确的方向!

关于javascript - 在嵌套指令中,为什么我的子指令获取父指令的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257379/

相关文章:

javascript - 为什么使用 Meteor.setInterval 调用方法会抛出 TypeError 异常?

javascript - 为什么 ng-table 不将数据从数组填充到表中?

javascript - 简单的 jQuery slider 脚本不起作用

javascript - 在 jquery 中隐藏单击按钮时的工具提示

javascript - 图片无限循环滚动

javascript - Linting jsx-a11y 向 div 元素添加角色

angularjs - 将解析与 angularjs 组件一起使用

php - 使用 laravel 访问 json 输入

javascript - jQuery 选择器无法识别任何动态创建的 HTML 输入函数

javascript - 如何使用 AWS 设置 AngularJS 应用程序?