星期三, 9月 10, 2014

[AngularJS] 如何在UI-Bootstrap取得input file

今天在使用DialogService的時候,在modal那層的controller一直取不到input file的$scope變數,查了一下在以下這篇討論:

http://stackoverflow.com/questions/23913998/how-to-access-file-input-in-controller-using-angular-ui-bootstrap-modal

解法如下:


透過自已新建一個fileService,再新增一個directive語法去記錄檔案改變時,將file存到fileService

HTML
<div ng-controller="ModalDemoCtrl">

    // Button to open model
    <button class="btn btn-default" data-ng-click="open()">Upload File</button>

    // Simple Form in model
    <script type="text/ng-template" id="myModalContent.html">
        <form name="form.myForm" class="form-horizontal" data-ng-submit="addFile()" role="form" novalidate>

            <div class="modal-header">
                <h3 class="modal-title">Upload File</h3>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="file" class="col-sm-2 control-label">Input File</label>

                    <div class="col-sm-10">
                        <input id="file" type="file" name="file" my-file-upload="">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-default">Submit</button>
            </div>

        </form>
    </script>

</div>
JS
var app = angular.module('app', ['ui.bootstrap']);

app.controller('ModalDemoCtrl', ['$scope', '$http', '$modal', function ($scope, $http, $modal) {

    $scope.open = function () {

        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            resolve: {
                $http: function () {
                    return $http;
                }
            }
        });

        modalInstance.result.then(function () {
            // do something
        }, function () {
            // do something
        });
    };

}]);

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $http, fileService) {

    $scope.addFile = function () {
        var file = fileService.getFile();
        console.log(file);
        $http.post(
            'http://posttestserver.com/post.php', file, {
                transformRequest: angular.identity,
                headers: {'Content-Type': file.type}
            }).success(function (data, status, headers, config) {
                console.log(data);
            });
    };
});

app.service('fileService', function () {
    var file;
    var fileService = {};

    fileService.getFile = function () {
        return file;
    };

    fileService.setFile = function (newFile) {
        file = newFile;
    };

    return fileService;
});

app.directive('myFileUpload', function (fileService) {
    return function (scope, element) {
        element.bind('change', function () {
            fileService.setFile(element[0].files[0]);
        });
    }
});

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails