我以前见过这些问题,通常是因为参数等,但我有一个非常简单的例子,我无法开始工作....
我有一个指令:
.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');
};
}])
所以,如果我打破这个:
有谁知道为什么?
答案 0 :(得分:0)
您很可能忘记将&#34;控制器指定为&#34; ng-controller
中的别名:
<div ng-controller="EditKitGraphicsController as controller">
<div image-file-input="controller.upload()">
</div>
此外,无需进行此项检查:
if (scope.onComplete){
scope.onComplete();
}
实际上,scope.onComplete
永远不会是undefined
,因为Angular会创建一个函数调用包装器,即使未分配该属性也是如此。你可以安全地拨打电话:
scope.onComplete();