js回调访问Angular作用域
Dropzone.js callback access Angular scope
我已经构建了一个简单的AngularJS指令来在元素上实现Dropzone.js。我想使用指令外的ng-repeat显示上传的文件,但我无法使其工作,因为元素的"adddedfile"回调似乎正在创建数组的副本(scope.files)。回调可以读取数组(或数组的副本),但当我推入一个新元素时,它不会影响ng-repeat。我怎样才能使它工作呢?
.directive('dropzone', function() {
return {
restrict: 'EA',
link: function(scope, el, attrs) {
el.dropzone({
url: attrs.url,
maxFilesize: attrs.maxsize,
init: function() {
scope.files.push({file: 'added'}); // here works
this.on('success', function(file, json) {
});
this.on('addedfile', function(file) {
scope.files.push({file: 'added'}); // here doesn't work
});
}
})
}
}
});
由于这种情况发生在Angular之外,你必须通过将其封装在$apply:
中来通知Angular。this.on('addedfile', function(file) {
scope.$apply(function(){
scope.files.push({file: 'added'});
});
});
如果你需要在angular中删除文件的功能,你可以使用这个轻量级指令:angular-file-upload
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
<div class="drop-box" ng-file-drop="onFileSelect($files);">drop files here</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
function dropZone() {
return function (scope, element, attrs) {
//scope.files="esto contiene files";
console.log(scope);
element.dropzone({
url: "upload.php",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 5,
init: function () {
scope.files.push({file: 'added'});
this.on('success', function (file, json) {
});
this.on('addedfile', function (file) {
scope.$apply(function () {
alert(file);
scope.files.push({file: 'added'});
});
});
this.on('drop', function (file) {
alert('file');
});
}
});
}
}
相关文章:
- 向Angular作用域对象添加对象数组——TypeError
- Angular中的作用域继承$broadcast
- 在Angular Bootstrap Modal和父控制器之间共享作用域
- 嵌套的Angular指令触发父对象上的作用域函数
- AngularJS-由$scope创建的作用域何时执行$new()已删除.垃圾收集器或Angular负责处理它吗
- 在Angular.js中通过检查作用域变量进行过滤
- 从$http.get调用更新Angular作用域变量
- 为什么Angular 1.5双向绑定在将作用域变量传递给组件绑定时失败
- Angular.js-从指令更新父作用域
- 如何在angular.js中为http控制器添加作用域
- 将Angular作用域变量的字符串描述传递给指令
- JavaScript 作用域和 Angular JS 作用域之间的区别是什么?
- 与隔离作用域的 Angular 双向绑定似乎是单向的
- iframe 中的 Angular js 作用域变量值
- 组合作用域后,字段在 Angular 中未正确重复
- Angular.js-视图不't在resize事件中更改作用域变量时更新
- 根据作用域变量为Angular指令提供一个模板
- angular,将变量设置为作用域名称
- angular会将我的对象推到作用域之外,或者将对象与我的提供程序合并
- 无法访问视图中的作用域-Angular