如何使用Javascript设置AngularJs属性

时间:2016-03-17 17:39:56

标签: javascript angularjs angularjs-directive

我的角度指令draggable1如下:

    angular.module('test', []).
    directive('draggable1', function($document) {


        return function(scope, element, attr) {
            var startX = 0,
                startY = 0,
                x = 0,
                y = 0;
            element.css({
                position: 'relative',
                cursor: 'pointer'
            });


            element.on('mousedown', function(event) {
                // Prevent default dragging of selected content
                event.preventDefault();
                //elementDragged = this;
                startX = event.screenX - x;
                startY = event.screenY - y;
                $document.on('mousemove', mousemove);
                $document.on('mouseup', mouseup);
            });

        /*  
        element[0].addEventListener('dragstart', function(e) {
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text', this.innerHTML);
        elementDragged = this;
            });
        */  

            function mousemove(event) {
                y = event.screenY - startY;
                x = event.screenX - startX;
                element.css({
                    top: y + 'px',
                    left: x + 'px'
                });
            }

            function mouseup() {
                $document.off('mousemove', mousemove);
                $document.off('mouseup', mouseup);
                //comparePositions();
            }




        };
    });

当我预定义时:

<li id="something" draggable1>Element One</li>
 it works completely fine, and I am able to drag my component.

但是当代码中的类似内容时,它不起作用,

<li id="something">Element One</li>
document.getElementById("something").setAttribute("draggable1",true)

我的element不动了。如何以正确的方式设置此attribute

1 个答案:

答案 0 :(得分:0)

您可以使用AngularJS的内置指令ng-if来检查条件并有条件地执行它。这样,您可以以条件方式应用指令。

示例:

<div ng-if="{some_condition}">
    <ul>
      <li id="something" draggable1></li>
   </ul> <!--Execute the directive on the basis of outcome of the if condition-->
</div>

其他示例

您可以将范围变量传递给指令并检查它是否为true / false或其他条件,然后应用您的代码。你的目标是在指令内部。希望这会对你有所帮助。