AngularJS中的范围问题

Scope issue in AngularJS

本文关键字:问题 范围 AngularJS      更新时间:2023-09-26

我目前正在玩AngularJS。我希望它开始好转,但我仍然有点困惑。我创建了一个拖放功能,该功能应该跟踪在目的地掉落的精灵,更改显示值等,...下面是一个示例:

http://codepen.io/anon/pen/wGxwJX

As it's a bit much code, I didn't paste it here,...

因此,它允许拖放并检查拖放字段是否接受正在拖动的类型。删除后,元素应记录在名为"items"的哈希图中,然后"test"链接将允许打印项目。

当我只删除一个项目时,当我单击"测试"链接时,这似乎有效。但是放下另一个项目,第一个就不再打印了。我怀疑我不明白的范围发生了一些事情,...

有什么想法吗?

$scope.handleDrop = function(e) {
  var dataID = e.dataTransfer.getData('text');
  $scope.$parent.fields[dataID][0] = $scope.$parent.fields[dataID][1];
  e.preventDefault();
  e.stopPropagation();

  $scope.$apply(function() {
    alert(dataID);
    $scope.$parent.items[this.id] = dataID;
    //$scope.$parent.items.push(dataID);
  });
  var item = document.getElementById(dataID);
  var f = eval("$scope.$parent." + item.getAttribute('drop-type'));
  this.innerHTML = '';
  this.appendChild(item);
  this.style.border = "1px solid";
};

您的问题是在 scope.$apply(function(){}) 中发生了变化;所以你需要把它分配给一些变量来使用它。试试这个,应该可以工作;

 $scope.handleDrop = function(e) {
  var self = this;
  var dataID = e.dataTransfer.getData('text');
  $scope.$parent.fields[dataID][0] = $scope.$parent.fields[dataID][1];
  e.preventDefault();
  e.stopPropagation();

  $scope.$apply(function() {
    $scope.$parent.items[self.id] = dataID;
    //$scope.$parent.items.push(dataID);
  });
  var item = document.getElementById(dataID);
  var f = eval("$scope.$parent." + item.getAttribute('drop-type'));
  this.innerHTML = '';
  this.appendChild(item);
  this.style.border = "1px solid";
};
$scope.$parent.items[this.id] = dataID; will add only the latest one and not all the values. 

您应该将项目作为数组,并将数据推送到其中,如下所示:


$scope.$parent.items.push[{this.id,dataID }];