Mischa
Mischa

Reputation: 1071

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

Upvotes: 8

Views: 1960

Answers (1)

Beyers
Beyers

Reputation: 9108

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

Upvotes: 8

Related Questions