首页 > 解决方案 > 无法在 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.
  };
}]);

有人可以帮我确定在第一种情况下我哪里出错了吗?

标签: htmlangularjsangularjs-directive

解决方案


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});
  });

推荐阅读