【问题标题】:Unable to invoke a custom directive inside another custom directive in AngularJs无法在 AngularJs 中的另一个自定义指令中调用自定义指令
【发布时间】: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-files directive 来进行重构。后者与ng-model 指令和ng-form 指令集成,提供与AngularJS 框架的更好集成。

标签: html angularjs angularjs-directive


【解决方案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});
  });

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多