[英]angularjs directive will not call controller function
我以前見過這些問題,通常是因為參數等,但我有一個非常簡單的例子,我無法開始工作....
我有一個指令:
.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');
};
}])
所以,如果我打破這個:
有誰知道為什么?
您很可能忘記在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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.