我不明白为什么如果我向一个指令的 Controller 内的数组添加更多元素,这些元素不会显示在 View 中,最糟糕的是,如果我打印模型,它不会显示添加的最新元素
这是我定义指令的方式
angular.module('example',[]);
angular.module('example').directive('documentUpload', function() {
function link($scope, $element, attrs, ngModelCtrl) {
$element.find('input[type="file"]').on('change', function (){
$scope.submitFile(this);
});
}
return {
restrict: 'E',
templateUrl: 'document-upload.html',
controller: function($scope,$element) {
$scope.files = [{ name : "blah", src: "blah" }];
$scope.submitFile = function(file,container) {
var currentFile = file.files[0];
var reader = new FileReader();
reader.onloadend = function(){
$scope.files.push({
name: currentFile.name,
src : reader.result
});
console.log($scope.files);
console.log($scope.example);
}
reader.readAsDataURL(currentFile);
};
},
alias: 'document',
link: link
}
}).directive('imageFiles', function($compile) {
return {
scope: {
file: "="
},
template: '<img ng-model="file" ng-src="file.src" alt="file.name" class="img-responsive"/>'
}
});
如果我尝试查看 View 中的模型未显示添加的最新元素,
<div class="row">
<pre>{{ files }}</pre>
<div class="col-lg-12">
<form method="POST" enctype="multipart/form-data" ng-submit="submit(document)">
<input type="file" name="file" ng-model="document.file"/>
</form>
</div>
<div class="row" ng-repeat="file in files" image-files>
这里是直播 Example
最佳答案
好的,这就是正在发生的事情。由于您使用的是 reader.onloadend,它是外部函数或插件,无论它是什么。它缺少内部 Angular 摘要过程。
在这种情况下,您需要在推送到数组后添加 $scope.$apply() 。
$scope.files.push({
name: currentFile.name,
src : reader.result
});
$scope.$apply();
这会强制 Angular 自行刷新。
为了安全起见,这是一个正在工作的笨蛋。
关于javascript - 无法更新指令模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820948/