как использовать область действия контроллера в директиве без использования опции контроллера в директиве - PullRequest
0 голосов
/ 11 марта 2019

Это мой код файла директивы

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>

Как удалить опцию контроллера из приведенного выше кода, а также как я могу заменить объект опции области видимости переменной контроллера.Пожалуйста, помогите мне решить эту проблему, потому что функция загрузки контроллера вызывает два раза из-за опции контроллера, поэтому я хочу это.

Ответы [ 2 ]

0 голосов
/ 13 марта 2019

Я нашел свое решение, если вы удалите опцию scope из директивы и переменную контекста контроллера доступа в шаблоне директивы, чем сможете решить эту проблему следующим образом. Вот мой обновленный код, который можно использовать для решения этого типа проблемы

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) {



                    console.log("VALUE OF USER INFO IN IMAGE DIRECTIVE");
                    console.log(rootScope.userInfo);

                    rootScope.userInfo.imageSrc = result;
                    rootScope.userInfo.profile_image_path = result;
                    rootScope.avatarFile = files[0];
                    rootScope.is_image_valid = true;



                    console.log("IN DIRECTIVE CODE IMAGE SRC");
                    console.log(rootScope.imageSrc);
                });
    });
  }

return {
    restrict: "EA",
    templateUrl: "/user/imageUploadTemplate",
    link: imageUploadLinker
};
}

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

angular
    .module("lugbeeUserSPA")
    .directive("imageUpload", imageUploadDirective);
0 голосов
/ 12 марта 2019

Я пересоздал сценарий с вашим кодом, и контроллер активируется только один раз. Проблема должна быть где-то еще.

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...