2014-10-08 112 views
0

所以我在尝试将某些工作的1.2.16代码迁移到1.3.0时遇到此问题。我已阅读发行说明,但一直未能找出到底是什么导致问题与控制器相同元素的自定义指令范围

它似乎归结为是我试图通过指令将自定义作用域分配给HTML元素这被定义为一个控制器。这在过去运行良好,我不知道如何解决它。

我的指令使事物'可拖动' - 它将数据从我的模型分配给本地HTML5的元素拖动&拖放。我的指令:

app.directive('draggable', function() { 
    return{ 
     scope: { 
      data : '=data' 
     }, 

     link : function(scope, element) { 
     // this gives us the native JS object 
     var el = element[0]; 

     el.draggable = true; 

     el.addEventListener('dragstart', function(e) { 
      e.dataTransfer.effectAllowed = 'move'; 

      e.dataTransfer.setData('Text', JSON.stringify(scope.data)); 
      this.classList.add('drag'); 
      return false; 
     }, false); 

     el.addEventListener('dragend', function(e) { 
      this.classList.remove('drag'); 
      return false; 
     }, false); 
    } 
    } 
}); 

我如何使用它:

`<div ng:repeat="step in pass.steps" ng:controller="StepEditorController" class="stepcontainer" draggable data="step">` 

我需要的指令,使这整个“步”元素可拖动。但是现在,我在指令中指定的自定义范围似乎给我带来了麻烦。我需要自定义作用域以获取该数据变量来定义正在拖动的数据。

再一次,这用于正常工作,但现在我得到一个multidir error,因为多个控制器正试图分配范围。

任何提示?这真让我抓狂。

+0

只是一个猜测,但ng-repeat已经创建了一个隔离范围,所以在指令中不需要另一个隔离范围。也许你可以用ng-init来传递数据属性的值... – 2014-10-08 12:19:10

回答

0

看起来您并不需要创建隔离范围,只需使用属性名称即可找到范围内的属性。

为了使您的指令与您定义它的元素具有相同的范围,请从指令定义中删除范围对象(或使用范围:true)。

然后确保你有属性的引用您的链接功能

link : function(scope, element, attributes) {...} 

而现在,而不是使用对指令的隔离范围值像以前一样,你可以使用属性名,你在你的属性指定访问范围对象

e.dataTransfer.setData('Text', JSON.stringify(scope[attributes.data])); 
// attributes.data is the name of the property on the scope 

这里的变量是所有的代码都在一起:

app.directive('draggable', function() { 
    return{ 
     //scope: { // omit the scope definition so you have the scope of the element itself 
     // data : '=data' 
     //}, 

     link : function(scope, element, attributes) { // you now need to use the attributes 
     // this gives us the native JS object 
     var el = element[0]; 

     el.draggable = true; 

     el.addEventListener('dragstart', function(e) { 
      e.dataTransfer.effectAllowed = 'move'; 

      // take the data from the scope directly using the attribute as the property name 
      e.dataTransfer.setData('Text', JSON.stringify(scope[attributes.data])); 
      this.classList.add('drag'); 
      return false; 
     }, false); 

     el.addEventListener('dragend', function(e) { 
      this.classList.remove('drag'); 
      return false; 
     }, false); 
    } 
    } 
}); 
相关问题