兄弟姐妹指令共享范围

时间:2014-04-11 13:07:37

标签: angularjs angularjs-directive angularjs-scope

我遇到了一个问题,通过一个指令,我试图在控制器的范围内设置一个属性。问题是,由于某种原因,指令的范围似乎是孤立自己,但仅限于此情况。它在应用程序的其他位置工作正常。因此,当我尝试在我的控制器中使用$scope.files时,它会以未定义的形式返回。

控制器:

app.controller('newProjectModalController', function($scope, $modalInstance, $http, $location, account, $http){

  $scope.account = account.data;

  $scope.project = {
    name: '',
    client: '',
    users: [],
    image: '/assets/images/add-project-photo.jpg'
  };

  $scope.cancel = function(){
    $modalInstance.dismiss('cancel');
  };

  $scope.updateImage = function(item){
    var filereader = new FileReader();
    filereader.readAsDataURL($scope.files.item(0));

    filereader.onload = function(event){
      $scope.project.image = event.target.result;
    }
  }

  $scope.submit = function(){
    var formData = new FormData();
    formData.append('file', $scope.files.item(0));

    $http.post($scope.api_url + '/Project', $scope.project)
      .success(function(data, status, headers, config){
        $modalInstance.close();
        $location.path('/project/' + data.id);
    });
  };
});

指令:

app.directive('fileUpload', function($parse){

    return {
        restrict: 'A',
        transclude: true,
        template: '<input type="file" name="file" multiple style="height:100%;width:100%;display:inline-block;opacity:0.0;position:absolute;top:0;left:0" />',

        link: function(scope, element, attrs){
            var onFileChange = $parse(attrs.fileUpload);
            var file = element.children('input');

            file.on('change', function(){
                scope.files = file[0].files;
                onFileChange(scope);
            })

        }
    }
});

模板:

<div class="row fieldset not" id="photo">
  <div class="col-sm-8 col-sm-offset-2">
    <h2 class="tight">Add project photo</h2>
    <div class="add-project-photo" file-upload="updateImage()" style="background-image: url({{project.image}})"></div>
    <span class="note">300px <i>by</i> 120px</span>
  </div>
</div>

模板只是部分...文件本身相当大

编辑:我应该提一下,使用UI-Bootstrap构建模态

1 个答案:

答案 0 :(得分:0)

由于您没有转发任何内容,因此您可以从transclude: true指令中删除fileUpload。您还可以设置scope: false以告诉指令使用父(控制器)范围。

app.directive('fileUpload', function($parse){

    return {
        restrict: 'A',
        scope: false,
        template: '<input type="file" name="file" multiple style="height:100%;width:100%;display:inline-block;opacity:0.0;position:absolute;top:0;left:0" />',

        link: function(scope, element, attrs){
            var onFileChange = $parse(attrs.fileUpload);
            var file = element.children('input');

            file.on('change', function(){
                scope.files = file[0].files;
                onFileChange(scope);
            })

        }
    }
});