如何在指令中使用控制器作用域而不在指令中使用控制器选项

时间:2019-03-11 05:51:26

标签: angularjs

  

这是我的指令文件代码

function imageUploadDirective(fileReader, rootScope) {

function imageUploadLinker(scope, elem, attr) {

    scope.$inputFileElement = elem.find(":file");

    scope.$inputFileElement.bind("change", function (e) {

        rootScope.invalid_image_msg = "";

        e.stopPropagation();
        var files = e.target.files === undefined ? (e.target && e.target.value ? [{
                name: e.target.value.replace(/^.+\\/, '')
            }] : []) : e.target.files;
        console.log("files: ", files);
        console.log("FILE ZERO INDEX");
        console.log(files[0]);

        if (files.length === 0 || files.length > 1 || !fileReader.isImageFile(files[0])) {

            if (!fileReader.isImageFile(files[0])) {
                rootScope.invalid_image_msg = "IT's Not an Image, Please Select Valid Format of Image";
            } else {
                rootScope.invalid_image_msg = "Please Select an Valid Image";
            }
            rootScope.is_image_valid = false;
            console.log("reset");
            scope.reset();
            return;
        }

        scope.fileName = files[0];
        fileReader
                .readAsDataUrl(scope.fileName, scope)
                .then(function (result) {

                    rootScope.userInfo.imageSrc = result;
                });
    });
}

return {
    restrict: "EA",
    templateUrl: "/user/imageUploadTemplate",
    scope: {
        name: "@",
        alt: "@",
        selectBtnTitle: "@",
        changeBtnTitle: "@",
        removeBtnTitle: "@",
        noImage: "@"
    },
    controller: "lugbeeUserSPACtrl",
    link: imageUploadLinker
};
}

imageUploadDirective.$inject = ["fileReader", "$rootScope"];

angular
    .module("lugbeeUserSPA")
    .directive("imageUpload", imageUploadDirective);
  

这是我的模板html文件代码

<div class="fileinput">

<div data-text="{{noImage}}" class="thumbnail image-upload-preview">
    <img ng-show="hostInfo.imageSrc" ng-src="{{hostInfo.profile_image_path}}" alt="{{imageSrc ? alt : ''}}">
</div>
<div>
    <span class="btn btn-default btn-file">
        <span ng-if="!fileName" ng-click="openFileSelector()">{{:: selectBtnTitle}}</span>
        <span ng-if="!!fileName" ng-click="openFileSelector()">{{:: changeBtnTitle}}</span>
        <input type="file" class="inputfile" name="{{:: name}}" id="{{:: name}}">
    </span>
    <a href="#" class="btn btn-default" ng-click="reset()" ng-if="!!fileName">{{:: removeBtnTitle}}</a>
</div>

如何从上面的代码中删除控制器选项,以及如何用控制器范围变量替换范围选项对象。 请帮助我解决此问题,因为由于控制器选项,控制器onload函数调用了两次,这就是我想要这样做的原因。

1 个答案:

答案 0 :(得分:0)

我用您的代码重新创建了一个方案,并且控制器仅被激活了一次。问题一定在其他地方。

function imageUploadDirective(fileReader, rootScope, $timeout) {

  function imageUploadLinker(scope, elem, attr, ngController) {

    ngController.onLoad("I have access to this method now also from the link function");

    scope.$inputFileElement = elem.find(":file");

    scope.$inputFileElement.bind("change", function(e) {
    
      rootScope.invalid_image_msg = "";

      e.stopPropagation();
      var files = e.target.files === undefined ? (e.target && e.target.value ? [{
        name: e.target.value.replace(/^.+\\/, '')
      }] : []) : e.target.files;
      console.log("files: ", files);
      console.log("FILE ZERO INDEX");
      console.log(files[0]);

      if (files.length === 0 || files.length > 1 || !fileReader.isImageFile(files[0])) {

        if (!fileReader.isImageFile(files[0])) {
          rootScope.invalid_image_msg = "IT's Not an Image, Please Select Valid Format of Image";
        } else {
          rootScope.invalid_image_msg = "Please Select an Valid Image";
        }
        rootScope.is_image_valid = false;
        console.log("reset");
        scope.reset();
        return;
      }

      scope.fileName = files[0];
      fileReader
        .readAsDataUrl(scope.fileName, scope)
        .then(function(result) {

          rootScope.userInfo.imageSrc = result;
        });
    });
  }

  return {
    restrict: "EA",
    templateUrl: "/user/imageUploadTemplate",
    scope: {
      name: "@",
      alt: "@",
      selectBtnTitle: "@",
      changeBtnTitle: "@",
      removeBtnTitle: "@",
      noImage: "@"
    },
    require: '^ngController',
    link: imageUploadLinker
  };
}

imageUploadDirective.$inject = ["fileReader", "$rootScope", "$timeout"];

angular
  .module('app', [])
  .directive('imageUpload', imageUploadDirective)
  .factory('fileReader', function() {
    return {};
  })
  .controller('lugbeeUserSPACtrl', function($scope) {
  
    this.onLoad = function onLoad(message) {
      console.log(message);
    };

    this.onLoad('controller activated when initialized in ngController');
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="app" ng-controller="lugbeeUserSPACtrl">

  <image-upload></image-upload>

  <script type="text/ng-template" id="/user/imageUploadTemplate">
    <div class="fileinput">
      <div data-text="{{noImage}}" class="thumbnail image-upload-preview">
        <img ng-show="hostInfo.imageSrc" ng-src="{{hostInfo.profile_image_path}}" alt="{{imageSrc ? alt : ''}}">
      </div>
      <div>
        <span class="btn btn-default btn-file">
        <span ng-if="!fileName" ng-click="openFileSelector()">{{:: selectBtnTitle}}</span>
        <span ng-if="!!fileName" ng-click="openFileSelector()">{{:: changeBtnTitle}}</span>
        <input type="file" class="inputfile" name="{{:: name}}" id="{{:: name}}">
        </span>
        <a href="#" class="btn btn-default" ng-click="reset()" ng-if="!!fileName">{{:: removeBtnTitle}}</a>
      </div>
  </script>
</body>