Search code examples
angularjsangularjs-directiveangularjs-ng-include

AngularJS 1.5 scope in directive ng-include


Here's some code http://jsfiddle.net/miuosh/n6yppypj/ with uploadfile directive. The problem is that I use this

  <input type="file" file-model="myFile" />
  <button ng-click="uploadFile()">upload me</button>

in ng-include="'views/uploadFileForm.html'".

In directive I add "myFile" to scope. It turns out that Angular create new scope with myFile. To add "myFile" to "rootScope" I need to use

modelSetter(scope.$parent.$parent.$parent[..],element[0].files[0])

which is inconvenient because I need to know how many parent scope I have.


Solution

  • I have faced similar problem dealing with file input with angular. you can create a directive which will listen to file change and call its controller function with file. Here jsFiddle for it.

    var app = angular.module('app', []);
    
    app.controller('yourCtrl', function() {
        $scope.image;
        $scope.imageChanged= function (files) {
            $scope.image = files;
        };
    });
    
    app.directive('customOnChange', function() {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var onChangeFunc = scope.$eval(attrs.customOnChange);
          element.bind('change', function(event){
            var files = event.target.files;
            onChangeFunc(files);
          });
    
          element.bind('click', function(){
            element.val('');
          });
        }
      };
    })
    
    <input type="file" id="imgInput" custom-on-change="imageChanged"/>