2016-01-11 5 views
1

Я пишу угловое приложение 1.5.0-rc0.выборка данных из угловой директивы

Я написал директиву image-upload, которая позволяет пользователю просматривать изображение и поворачивать его. директива может получить свойство с именем image с URL-адресом изображения.

код директивы:

angular.module('myalcoholist').directive('imageUpload',[ 
    function() { 
     return { 
      restrict: 'E', 
      templateUrl: 'views/image-upload.html', 
      scope: { 
       image: '=' 
      }, 
      link: function(scope, elem, attrs) { 

       scope.$watch(function() { 
         return scope.image 
        }, 
        function(newValue, oldValue) { 
         var val = newValue || null; 
         $('#upload-img').attr('src',val); 
        }); 
      }, 
      controller: ['$scope', function($scope) { 
       $scope.imageRotateDegrees=0; 
       $scope.imageExifRotation=0; 
       $scope.isImageFileExif=false; 
       if ($scope.imageUrl) { 
        $('#upload-img').attr('src',$scope.imageUrl); 
       } 
       $scope.imageChanged = function (e) { 
        var imageFile = e.files[0]; 
        var img = $('#upload-img'); 
        var reader = new FileReader(); 
        reader.onload = function (e) { 
         var exif = EXIF.readFromBinaryFile(e.target.result); 
         switch (exif.Orientation) { 
          case 8: 
           $scope.$apply(function() { 
            $scope.imageRotateDegrees=-90; 
            $scope.imageExifRotation=-90; 
            $scope.isImageFileExif=true; 
           }) 
           img.css('transform', 'rotate(-90deg)'); 
           break; 
          case 3: 
           $scope.$apply(function() { 
            $scope.imageRotateDegrees=180; 
            $scope.imageExifRotation=180; 
            $scope.isImageFileExif=true; 
           }) 
           img.css('transform', 'rotate(180deg)'); 
           break; 
          case 6: 
           $scope.$apply(function() { 
            $scope.isImageFileExif=true; 
            $scope.imageExifRotation=90; 
            $scope.imageRotateDegrees=90; 
           }) 
           img.css('transform', 'rotate(90deg)'); 
           break; 
          default: 
           $scope.$apply(function() { 
            $scope.isImageFileExif=false; 
           }) 
         } 
        } 
        var reader2 = new FileReader(); 
        reader2.onload = function(e) { 
         img.attr('src', e.target.result); 
        } 
        reader.readAsArrayBuffer(imageFile); 
        reader2.readAsDataURL(imageFile); 
       } 
       $scope.rotateImageLeft = function() { 
        $scope.imageRotateDegrees=($scope.imageRotateDegrees-90)%360; 
        $('#upload-img').css('transform','rotate(' + $scope.imageRotateDegrees + 'deg)'); 
       } 
       $scope.rotateImageRight = function() { 
        $scope.imageRotateDegrees=($scope.imageRotateDegrees+90)%360; 
        $('#upload-img').css('transform','rotate(' + $scope.imageRotateDegrees + 'deg)'); 
       } 
       $scope.rotateImage180deg = function() { 
        $scope.imageRotateDegrees=($scope.imageRotateDegrees+180)%360; 
        $('#upload-img').css('transform','rotate(' + $scope.imageRotateDegrees + 'deg)'); 
       } 
       $scope.rotateByExif = function() { 
        $('#upload-img').css('transform','rotate(' + $scope.imageExifRotation + 'deg)'); 
        $scope.imageRotateDegrees=$scope.imageExifRotation; 
       } 
      }], 
     } 
    } 
]); 

image-upload.html файл шаблона

<div class="container"> 
<div class="row"> 
    <div class="col-md-2"> 
     <input id="image-upload-file" type="file" file-model="imageFile" onchange="angular.element(this).scope().imageChanged(this)" class="form-control" accept="image/*" /> 
    </div> 
    <div class="col-md-2"> 
     <button class="form-control" ng-disabled="!imageFile && !image" ng-click="rotateImageLeft()" type="button">Rotate Left</button> 
    </div> 
    <div class="col-md-2"> 
     <button class="form-control" ng-disabled="!imageFile && !image" ng-click="rotateImageRight()" type="button">Rotate Right</button> 
    </div> 
    <div class="col-md-2"> 
     <button class="form-control" ng-disabled="!imageFile && !image" ng-click="rotateImage180deg()" type="button">Rotate 180deg</button> 
    </div> 
    <div class="col-md-2"> 
     <button class="form-control" ng-disabled="!isImageFileExif" ng-click="rotateByExif()" type="button">Rotate by EXIF</button> 
    </div> 
    <div class="col-md-2"> 
     <span ng-bind="imageRotateDegrees"></span>deg 
    </div> 
</div> 
<hr /> 
<div class="row"> 
    <div class="col-md-6 col-md-offset-3" style="overflow: scroll;"> 
     <img id="upload-img" /> 
    </div> 
</div> 
<hr /> 
</div> 

директива работает, до сих пор так хорошо.

Теперь я хочу, чтобы иметь возможность извлекать данные из этой директивы, в моем случае мне нужно получить данные файла изображения и степени вращения.

Как я могу получить данные от вызывающего контроллера?

благодарю

ответ

0

я работала решение с помощью двунаправленного связывания с областью применения директивы.

означает, что я добавил следующий код директивы кода конфигурации:

scope: { 
     imageRotqteDegrees='=' 
} 

это добавляет imageRotateDegrees к $scope и позволяет мне использовать image-rotate-degrees как Собственость к image-upload.

так, если я выполнить директиву следующего кода:

<image-upload image-rotate-degrees="MyController.MyVar"></image-upload> 

он связывается с переменным контроллером называется MyVar

0

Вы должны использовать угловую службу для обработки связи между директивой и контроллером ,

Вы также должны рассмотреть возможность переноса большей части своей логики на тот же сервис.

+0

спасибо за отзыв. но я не понимаю, почему и как, если возможно, создайте jsfiddle для этого, чтобы я понял его более правильно. – ufk

Смежные вопросы