【发布时间】:2015-07-08 16:47:07
【问题描述】:
我以前见过这些问题,通常是因为参数等,但我有一个非常简单的例子,我无法开始工作......
我有一个指令:
.directive('imageFileInput', function () {
return {
restrict: 'A',
transclude: true,
templateUrl: '/assets/tpl/directives/imageFileInput.html',
scope: {
onComplete: "&imageFileInput"
},
link: function (scope, element, attr) {
// Get our input
var input = element.find("input");
// Function to handle the displaying of previews
var preview = function () {
// If we have an input
if (input) {
// Create our file reader
var fileReader = new FileReader();
// Get our file
var file = input[0].files[0];
// Read the data from the file
fileReader.readAsDataURL(file);
// When the data has been read
fileReader.onload = function (e) {
// Apply the scope
scope.$apply(function () {
// And attach the result to our scope
scope.thumbnail = e.target.result;
// If we have a callback function
if (scope.onComplete) {
// Execute the function
scope.onComplete();
}
});
};
}
};
// Bind a function to the onchange event
input.bind('change', function () {
// Create our preview
preview();
});
}
};
});
模板看起来像这样:
<div class="thumbnail">
<input type="file" accept="image/*" />
<img src="{{ thumbnail }}" ng-if="thumbnail" />
<div class="caption" ng-transclude>
</div>
</div>
到目前为止非常简单,它只是一个为文件输入创建漂亮预览的指令。 所以这个指令的声明在我看来是这样的:
<div id="{{ panel.id }}" image-file-input="controller.upload()">
{{ panel.title }}
</div>
在我的控制器中,我有这个功能:
.controller('EditKitGraphicsController', ['GarmentService', 'garment', function (garments, garment) {
var self = this;
// Get our garment
self.garment = garment;
self.upload = function () {
console.log('uploading');
};
}])
所以,如果我分解一下:
- 我的指令隔离了作用域,并需要一个名为 onComplete 的回调函数,它与指令声明一起传递(即 image-file-input="callback()")
- 我的指令在 scope.$apply 之后调用此函数,并且在检查回调函数是否存在后,没有传递任何参数
- 我的视图传递了控制器函数upload(),它又没有参数
- 我的控制器有一个附加到范围的函数,称为上传,其中有一个 console.log
- 但没有执行任何操作...
有人知道为什么吗?
【问题讨论】:
标签: javascript angularjs