无法在AngularJs的另一个自定义指令内调用自定义指令

时间:2020-07-08 06:12:06

标签: html angularjs angularjs-directive

我想在另一个自定义指令的模板中调用一个自定义指令。 请在下面找到代码段-

方案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"/>

上传文件时收到的错误-

未捕获的TypeError:onChangeFunc不是函数

方案2(正在运行)

尽管可以独立地从index.html调用customOnChange指令。工作代码段-

index.html

<input type="file" ng-model="file" name="file"
       id="photo-upload1" custom-on-change="changeUserProfileImage"
       value="Change Image"
       title="Change Image"/>

myCtrl.js

angular.module('myApp')
.controller('myCtrl', ['$scope', function ($scope) {
  $scope.changeUserProfileImage = function (files) {
     console.log(files); // I am receiving uploaded files here.
  };
}]);

有人可以帮助我确定第一种情况下我要去哪里吗?

1 个答案:

答案 0 :(得分:1)

指令定义中的

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});
  });
相关问题