ondragstart, ondragover,onstart - $scope is not defined
Asked Answered
R

2

6

My task is to process the dropped text using angular. I keep getting this error $scope is not defined on drag and drop events. Any idea how to fix this?

I already looked into angular drag and drop libraries. They don't allow drag and drop for simple text. Most of them work with lists. Let me know if there is one that works for this task

Here is the plunker:

[http://plnkr.co/edit/egKL13hsHka6RiX4UfSS?p=preview][1]

here is the controller:

var app = angular.module("test",  []);
app.controller('testCtrl', ['$scope',function  ($scope) {
   $scope.nouns = ['guitar'];
   $scope.verbs = ['play'];
   $scope.allowDrop= function (ev) {
        ev.preventDefault();
   };
   $scope.drag=  function (ev) {
        ev.dataTransfer.setData("Text", ev.target.id);
   };    
   $scope.drop=  function (ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("Text");
        if(ev.target.id =='verb' && $scope.verbs.indexOf(data) != -1){
            ev.target.appendChild(document.getElementById(data));
        }
        else{
            alert(data + ' is not a ' + ev.target.id +'. Try again');
        }            
    };      
  }]);
Rackrent answered 12/5, 2015 at 19:40 Comment(5)
In your html you are using $scope.drag. You don't need the $scope. Just use drag($event).Accordion
Now it says "Uncaught ReferenceError: drag is not defined , allowDrop is not defined".Rackrent
Sorry, I was being stupid. You can't do what you were doing in Angular the way you are doing it. i.e. you can't put $scope functions in regular attributes. You have to use the ng-<event> versions. And there aren't any for drag and drop events. You need to use something like ngDraggableAccordion
I already looked into ng-Draggable like libraries. I can't find one that allows drag and drop simple text. They all work with lists or Html elements.Rackrent
If you surround your text with a <span>text</span> element then it will be an HTML element and maybe you can use the ng-draggable library?Accordion
M
6

$scope object will not available in "Outside angular context". Whenever you want to access angular scope in JavaScript (Outside angular world) then you need to get the scope of by getting the DOM of that element & then access the scope of it like angular.element(document.getElementById('testApp')) which is nothing but scope of the body.

Working Plunkr

Refer this SO answers to get access to the scope outside angular context.

Melancholia answered 12/5, 2015 at 21:2 Comment(1)
@kumaro glad to help you..it would be more elegant if you do this by using directive..Melancholia
C
2

a shorter one based on @pankaj-parkar answer :

<div draggable="true" ondrag="angular.element(this).scope().on_drag(event)"></div>
Cinquecento answered 8/3, 2017 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.