2014-10-07 62 views
0

我有這條指令,它基本上通過file-model="..."將文件附加到模型中(此指令的全部目的是因爲ng-model<input type="file">中不起作用angularjs)在指令中收到的範圍與指令真正生活的範圍不一樣

angular.module('myApp').directive('fileModel', ['$parse', function ($parse) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 

      console.log(scope); // DEBUG 

      var model = $parse(attrs.fileModel); 

      element.bind('change', function() { 
       scope.$apply(function() { 
        model.assign(scope, element[0].files[0]); 
       }); 

       if (attrs.ngChange) { 
        scope.$apply(attrs.ngChange); 
       } 
      }); 
     } 
    }; 
}]); 

而且我也有一個引導的UI模式,modal.html:

<div class="modal-body"> 
    <div class="form-group"> 
     <input type="file" file-model="excelFile" ng-model="dummy" ng-change="uploadFile()" /> 
    </div> 
</div> 

與其對應的引導,UI CONTRO米勒:

angular.module('myApp').controller('modalController', ['$scope', '$modalInstance', '$scope', function ($scope, $modalInstance, $scope) { 

    $scope.uploadFile = function() { 
     console.log($scope); // DEBUG 

     var formData = new FormData(); 
     formData.append('file', $scope.excelFile); // empty! 

     ... 
    }; 
}]); 

我調用模式從另一個控制器是這樣的:

$scope.openModal = function() { 

    var modalScope = $scope.$new(); 

    modalScope.somePassedData = "I pass data this way"; 

    var modalInstance = $modal.open({ 
     templateUrl: 'views/modal.html', 
     controller: 'modalController', 
     scope: modalScope, 
    }); 

    ... 
}; 

所以...如果你注意到了三點意見:

  1. 首評// DEBUG
  2. 二評論// DEBUG
  3. 評論// empty!

看來,由指令使用的範圍是不一樣的,其中<input type="file">是生活的範圍,也正因爲如此,我得到一個空文件。

我在做什麼樣的範圍錯誤?

而且我應該指出,這個工作得很好,而無需使用引導界面模態...所以它必須有一些與模態

+0

答案在這裏:'var modalScope = $ scope。$ new();'。 '$ scope。$ new()'創建一個從'$ scope'繼承的新的子範圍。因此'$ scope'中的任何內容都應該在'modalScope'中。但是你說你「從另一個控制器調用模態」。控制器具有獨立的作用域,所以'$ scope.excelFile'很可能位於另一個作用域而不是'modalScope',對吧? – 2014-10-07 14:32:05

+0

你已經看到[這個相關的SO帖子](http://stackoverflow.com/questions/18716113/scope-issue-in-angularjs-using-angularui-bootstrap-modal?rq=1)正確,你試圖初始化'$ scope.input = {}'並且它不起作用? – Michael 2014-10-07 14:32:19

+0

對不起,我沒有關注你......但我曾嘗試初始化$ scope.excelFile在模態 – sports 2014-10-07 14:40:59

回答

0

兩件事情的範圍做測試:

  1. 驗證您的uploadFile函數在之後調用您的指令的事件處理程序(因爲它們正在偵聽相同的事件)。如果不是,則應增加fileModel指令的優先級,使其大於ngChange(即0)的優先級。
  2. 嘗試使用resolve屬性將數據傳遞到您的模態,而不是創建新的作用域。根據文檔,$modal創建了一個你傳入的子範圍,所以你可能會遇到與原始值有關的原型繼承問題。
+0

關於(1):在uploadFile()方法(選中)之前調用所有指令代碼。關於(2):嗯,我會嘗試,即使對於我過去的所有模式,我已經從父母傳遞一個新的範圍 – sports 2014-10-07 18:35:58