Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope variable and ng-include in Angular are not harmonizing

I have a file dropzone to get data content of a file.
If I set the $scope.importData to null, it is not possible to assign data inside the drop handler anymore.

$scope.handleDrop = function(evt) {
    if (window.File && window.FileReader && window.FileList && window.Blob) {
      var files = evt.dataTransfer ? evt.dataTransfer.files : evt.target.files,
          file = files[0],
          reader = new FileReader();

      reader.onloadend = function(evt) {
          var content = evt.target.result;
          if('' !== content) {
              $scope.importData = content; //will work as long you do not set $scope.importData to null
              $scope.$apply();
          }
      };
      reader.readAsText(file);
    }
};

I figured out the problem might be the ng-include. If I do it without the include, it will work.

Please try the Plunker...

http://plnkr.co/edit/BFOquRMLOqpL3arv1rtI?p=preview

like image 439
Mischa Avatar asked Jan 02 '14 11:01

Mischa


People also ask

What is the scope in angular 9?

AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.

Does Ng include create a new scope?

The ng-include directive is executed at priority level -400 and creates new scope every time it is invoked.


1 Answers

ngInclude creates a new scope that prototypically inherits from its parent scope, in your plunker example the parent scope being the scope of your pageCtrl. The problem with your example is that inside $scope.addSetReImport you are setting var $scope = this; and in that context this refers to ngInclude's scope and not your pageCtrl scope, so $scope.importData = null; effectively overrides the prototype importData variable with a property on ngInclude's scope. The following screenshot from Chrome's console illustrates this override, this is from ngInclude's $scope:

enter image description here

So you end up with two importData variables, one sitting on your ngInclude's scope and used inside your modal template, which is pointing to null, and a second one that sits on your pageCtrl scope that is used during the handleDrop function. Since handleDrop will update the importData on the pageCtrl scope, it will not reflect on the property set on the ngInclude scope that your template is using.

To get your example working, just remove the var $scope = this; from your addSetReImport function, this ensures you are referencing the scope of your pageCtrl. Here is a cloned plunker with a working example: http://plnkr.co/edit/LvYGKqLlL9Pxq0X5slyM?p=preview

like image 119
Beyers Avatar answered Oct 01 '22 19:10

Beyers