gpt4 book ai didi

javascript - angularjs 指令不会调用 Controller 函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:42:50 25 4
gpt4 key购买 nike

我以前见过这些问题,通常是因为参数等,但我有一个非常简单的例子,我无法开始工作....

我有一个指令:

.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 中,我有这个功能:

.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()")一起传递
  • 我的指令在作用域后调用此函数。$apply 并检查回调函数是否存在后,没有传递任何参数
  • 我的 View 传递了同样没有参数的 Controller 函数 upload()
  • 我的 Controller 有一个功能附加到名为上传的范围,其中有一个 console.log
  • 然而什么都没有执行...

有人知道为什么吗?

最佳答案

您很可能忘记在 ng-controller 中指定一个“controller as”别名:

<div ng-controller="EditKitGraphicsController as controller">
<div image-file-input="controller.upload()">
</div>

此外,无需进行此检查:

if (scope.onComplete){
scope.onComplete();
}

事实上,scope.onComplete 永远不会是undefined,因为 Angular 创建了一个函数调用包装器,即使属性没有被赋值。您可以安全地调用电话:

scope.onComplete();

关于javascript - angularjs 指令不会调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31298807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com