简体   繁体   中英

Scope issue in AngularJS

I'm currently playing around with AngularJS. It starts getting better I hope, but I'm still a bit confused. I created a drag-drop functionality that should keep track of the elments being dropped at the destination, change display values and so on,... Here is an example:

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

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

So it allows drag drop with checking if the drop field accepts the type being dragged. After the drop, the element should be recorded in a hashmap called 'items', the 'test' link would then allow to print the items.

When I just drop one item, that seems to work when I click the 'test' link. But dropping another item, the first doesn't get printed anymore. I suspect that there happens something with the scopes I don't understand,...

Any ideas?

$scope.$parent.items[this.id] = dataID; will add only the latest one and not all the values. 

You should be having items as an array and push data into it like this:


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

$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";
};

Your issue is that this is changed in scope.$apply(function(){}); So you need assign it to some variable to use it. Try this, should work;

 $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";
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM