【发布时间】:2020-10-28 11:56:31
【问题描述】:
我想在另一个自定义指令的模板中调用一个自定义指令。 请在下面找到代码 sn-ps -
场景 1(不工作)
angular.module('myApp')
.directive('customOnChange', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var onChangeFunc = scope.$eval(attrs.customOnChange);
element.bind('change', function (event) {
var files = event.target.files;
onChangeFunc(files);
});
element.bind('click', function () {
element.val('');
});
}
};
})
.directive('writePost', function () {
return {
restrict: 'E',
link: function (scope) {
scope.changeUserProfileImage = function (files) {
console.log(files); // I should receive uploaded files here.
};
},
templateUrl: function () {
return 'writePost.html';
}
};
});
index.html
<write-post></write-post>
writePost.html
<input type="file" ng-model="file" name="file"
id="photo-upload1" custom-on-change="changeUserProfileImage"
value="Change Image"
title="Change Image"/>
我上传文件时收到的错误 -
未捕获的类型错误:onChangeFunc 不是函数
场景 2(工作)
虽然我可以独立地从 index.html 调用 customOnChange 指令。工作代码 sn -p -
index.html
<input type="file" ng-model="file" name="file"
id="photo-upload1" custom-on-change="changeUserProfileImage"
value="Change Image"
title="Change Image"/>
我的Ctrl.js
angular.module('myApp')
.controller('myCtrl', ['$scope', function ($scope) {
$scope.changeUserProfileImage = function (files) {
console.log(files); // I am receiving uploaded files here.
};
}]);
有人可以帮我确定在第一种情况下我哪里出错了吗?
【问题讨论】:
-
考虑通过将
customOnChange指令替换为select-ng-filesdirective 来进行重构。后者与ng-model指令和ng-form指令集成,提供与AngularJS 框架的更好集成。
标签: html angularjs angularjs-directive