Javascript 与控制器位于同一元素中的自定义指令范围
因此,我在尝试将一些正在运行的1.2.16代码迁移到1.3.0时遇到了这个问题。我已经阅读了发行说明,但还没有找到问题的确切原因 归结起来,我试图通过指令将自定义范围分配给定义为控制器的HTML元素。这在过去很管用,我不知道该怎么解决 我的指令使事物“可拖动”——它将数据从我的模型分配给本地HTML5拖放的元素。我的指示:Javascript 与控制器位于同一元素中的自定义指令范围,javascript,html,angularjs,controllers,Javascript,Html,Angularjs,Controllers,因此,我在尝试将一些正在运行的1.2.16代码迁移到1.3.0时遇到了这个问题。我已经阅读了发行说明,但还没有找到问题的确切原因 归结起来,我试图通过指令将自定义范围分配给定义为控制器的HTML元素。这在过去很管用,我不知道该怎么解决 我的指令使事物“可拖动”——它将数据从我的模型分配给本地HTML5拖放的元素。我的指示: app.directive('draggable', function() { return{ scope: { data :
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">`
我需要指令使整个“步骤”元素可拖动。但是现在,我在指令中指定的自定义范围似乎给我带来了麻烦。我需要自定义范围,以便获取该数据变量以定义要拖动的数据
同样,这过去工作得很好,但现在我得到了一个答案,因为多个控制器正试图分配作用域
有什么提示吗?这让我快发疯了 似乎不需要创建隔离作用域,只需使用属性名称查找作用域上的属性即可 为了使指令与定义它的元素具有相同的作用域,请从指令定义中删除scope对象或使用scope:true 然后确保在链接函数中有对属性的引用
link : function(scope, element, attributes) {...}
现在,您可以使用在属性中指定的属性名来访问scope对象中的变量,而不是像以前那样在指令的独立作用域上使用值
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);
}
}
});
只是一个猜测,但是ng repeat已经创建了一个隔离作用域,所以在指令中不需要另一个隔离作用域。也许您可以使用ng init传递数据属性的值。。。