我有一个指令,将文件上传输入字段放置在 DOM 上,然后我希望能够在该文件更改时调用函数。如何在不将 on-change 函数放置在编译器区域的情况下使其工作?我知道它不属于那里,因为我被告知编译器更加占用内存,并且只能用于预渲染的东西。
angular.module('myApp').directive('customDirective', ['$http', function ($http) {
return {
controller() {
},
compile(element) {
const $fileinput = $('<input type="file" accept=".csv">').appendTo(element);
return {
controller: () => {
$fileinput.on('change', (e) => {
// Stuff happens
});
},
link: () => {
},
};
},
};
}]);
最佳答案
试试这个:
<p>
Select a file, and you should see an alert message
</p>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="file" custom-on-change="uploadFile"/>
</div>
var myApp = angular.module('myApp', []);
myApp.directive('customOnChange', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeFunc = scope.$eval(attrs.customOnChange);
element.bind('change', onChangeFunc);
}
};
});
myApp.controller('myCtrl', function($scope) {
$scope.uploadFile = function(){
var filename = event.target.files[0].name;
alert('file was selected: ' + filename);
};
});
这是工作fiddle
关于jquery - Angular 自定义指令在输入字段更改时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38148815/