2015-11-11 60 views
0

我試圖創建一個可拖動的div並綁定到它的位置,以便我可以在其他地方使用該位置。我需要多個可拖動的元素。到目前爲止,我已經創建了一個「dragable」屬性指令,並且可以根據需要在頁面周圍拖動元素,我使用'x'和'y'屬性設置了初始位置。綁定到指令屬性

<body ng-app="myApp" ng-controller="myCtrl"> 
    <div dragable x="50" y="50" style="...."></div> 
    <p> 
     x: {{x_loc}}<br/> 
     y: {{y_loc}} 
    </p> 
<body> 

問題是,當我嘗試添加綁定「X」和「y」到變量在myCtrl範圍

<div dragable x="{{x_loc}}" y="{{y_loc}}" style="...."></div> 

這產生了普通的無效表達錯誤。我的指令如下所示:

app.directive("dragable", function($document) { 
    dragable = {}; 

    dragable.restrict = 'A', 
    dragable.link = function(scope, element, attrs) { 

     element.css({ 
      top: scope.y + 'px', 
      left: scope.x + 'px' 
     }); 

     function select(evt) { 
      ...   // get initial conditions 
      $document.on('mousemove',move); 
      $document.on('mouseup',deselect); 
     }; 

     function move(evt){ 
      ...   //do some error checking then 
         //update the element location 
     }; 

     function deselect(evt){ 
      $document.unbind('mousemove',move); 
      $document.unbind('mouseup',deselect); 
     };   

     $document.on('mousedown', select); 
    }; 
    dragable.scope = { 
     x: "=", 
     y: "=", 
    }; 

    return dragable; 
}); 

任何建議都會有幫助。提前致謝。而不是

+0

如果你正在做一個2路中的括號去掉綁定在你的指令中,那麼你不應該在你的屬性中使用表達式。只要'

'就可以了。 – user2718281

回答

1
<div dragable x="x_loc" y="y_loc" style="...."></div> 

<div dragable x="{{x_loc}}" y="{{y_loc}}" style="...."></div> 

因爲

dragable.scope = { 
    x: "=", 
    y: "=", 
}; 

如果使用x: "@"x="{{x_loc}}"意志工作

https://jsfiddle.net/1x0bxncp/1/

0

我認爲dragable.scope = {}存在問題。

  • 一種方式屬性綁定
    使用{{}}支架。在範圍內使用x: "@x_loc"
  • 雙向綁定
    使用從範圍值,沒有括號。在範圍內使用y: "=y_loc"
    您可以在這裏省略x: "=x_loc"如果他們相同。像這樣x: "="
0

你需要從作用域屬性<div dragable x="x_loc" y="y_loc" style="...."></div>

還需要添加position:absolute到你的CSS樣式

you can see it here