2014-11-05 59 views
0

我在使用ngRepeat指令時遇到問題。我不能得到$ scope.files的價值。它在使用內部ngrepeat時未定義,但在不使用ngrepeat時正常工作。不能弄明白。非常感謝。ng-repeat內部指令不起作用

$ scope.files在ng-repeat中使用時未定義。如果不使用內部完美的作品

<button class="btn btn-success login-button" ng-click="addassignment()">+</button> 
<table> 
    <tr ng-repeat = "assignment in assignments"> 
     <td><input class = "filegap" type = "file" file-model="form.cv" ng-model="form.cv" ng-file-select="fileselected(newemp.email)" file-input="files" multiple/></td> 
    </tr> 
</table> 

的javascript:

app.directive('fileInput', ['$parse', function($parse, $compile){ 
    return { 
     restrict:'A', 
     link:function(scope,elm,attrs){ 
      elm.bind('change', function(){ 
       $parse(attrs.fileInput) 
       .assign(scope,elm[0].files) 
       scope.$apply() 
      }) 
     } 
    } 
}]); 

控制器:

$scope.addassignment = function(){ 
    if(typeof $scope.assignments == 'undefined'){ 
     $scope.assignments = []; 
    } 
    $scope.assignments.push({}); 
} 
console.log($scope.files); 
+1

定義的作業在哪裏? – Pogrindis 2014-11-05 14:30:34

+0

賦值在控制器中定義,用於動態生成輸入。那不是問題的問題是在ng-repeat內的指令文件輸入。 – 2014-11-05 14:33:21

+1

我發現你給這個代碼真的很難遵循..你可能提供更多關於你想要實現的信息嗎?爲每個作業上傳一個文件?所有在一起或單獨? – Pogrindis 2014-11-05 14:36:01

回答

1

你不上主要適用範圍創建一個文件變量,當你使用assign它會分配給一個新創建的文件(不在控制器上),我修改了你的代碼了一下,

angular.module('myApp',[]).controller('Main', ['$scope', function($scope) { 
    $scope.files = []; 
    $scope.addAssignment = function(){ 
    if(typeof $scope.assignments == 'undefined'){ 
     $scope.assignments = []; 
    } 
    console.log('add'); 
    $scope.assignments.push({}); 
    } 
    console.log($scope.files); 
    $scope.$watch('files.length', function() { 
    console.log($scope.files); 
    }); 
}]).directive('fileInput', [function() { 
    return { 
     restrict:'A', 
     link:function(scope,elm,attrs){ 
       var files = scope[attrs['fileInput']]; 
      elm.bind('change', function(){ 
       files.push(this.files); 
       scope.$apply() 
      }); 
     } 
    } 
}]); 

,你可以看看這裏: http://plnkr.co/edit/mhXKdlDG5lg8Xnw50lua?p=preview

附:您也可以在指令中使用作用域綁定而不是$ parse。另外,當你直接指定的時候,它會一直覆蓋文件,因爲原型繼承在JS中是如何工作的,使用對象/數組代替在更深的範圍內賦值(如ng-model/ng-repeat等)。 )

+2

短版本:[ng-repeat創建自己的作用域](https://docs.angularjs.org/api/ng/directive/ngRepeat),所以你必須在其外部初始化'files'。 – Blazemonger 2014-11-05 15:14:40

+0

console.log必須輸出一個像這樣的文件.FileList {0:File,length:1,item:function} 0:Filelength:1__proto__:FileList – 2014-11-05 15:32:14

+0

爲什麼「必須」它?看到所有'$ scope.files'有什麼不對?哪個'console.log'? – Blazemonger 2014-11-05 15:47:35