html - 无法在 AngularJs 中的另一个自定义指令中调用自定义指令
问题描述
我想在另一个自定义指令的模板中调用一个自定义指令。请在下面找到代码片段 -
场景 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';
}
};
});
索引.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 指令。工作代码片段 -
索引.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.
};
}]);
有人可以帮我确定在第一种情况下我哪里出错了吗?
解决方案
link
在指令定义中默认为postLink
- 它在模板及其指令被解析后执行。(在这里阅读更多https://docs.angularjs.org/api/ng/service/$compile#pre-linking-function)
作为一种解决方案,您可以在回调中移动 $eval:
element.bind('change', function (event) {
var onChangeFunc = scope.$eval(attrs.customOnChange);
var files = event.target.files;
onChangeFunc(files);
});
正确方法:
如果你想要运行函数 - 让它在 html 中运行:
custom-on-change="changeUserProfileImage(files)"
现在将其作为函数运行:
element.bind('change', function (event) {
var files = event.target.files;
scope.$eval(attrs.customOnChange, {files: event.target.files});
});
推荐阅读
- github - 有没有办法在 Github 上隐藏分支?
- javascript - 单击连字符最小化按钮的奇怪问题
- pandas - SAS Do 循环到 Pandas 创建新变量
- spring-security - Spring 原生 - CustomAuthenticationManager (ReactiveAuthenticationManager)
- python - 我有一个 automod 设置,但是当我尝试在用户触发事件时提及用户时,我收到一个 ctx 错误,它说未定义作者
- android - 任务“:app:checkDebugAarMetadata”执行失败。当我尝试在 Android Studio 中运行我的程序时
- python - Pandas.Series.Str.Find 在列表中与 x 混合
- python - Numpy 生成更快的逆矩阵
- python - 如何强制 Tensorflow 将 tcmalloc-minimal4 用于 tf.data?
- android - 如何在 Android 中裁剪图像