-->

Directive to get files input with ng-model [duplic

2020-01-30 02:58发布

问题:

Guyz i have an issue with my code i don't know why when i tried to get file from <input ng-model="form.userfile" id="itemImage" name="userfile" type="file"> that code will not give me the values.

my code:

HTML:

<div class="panel panel-default">
    <div class="panel-body">
    <form id="form" accept-charset="utf-8" ng-submit="sendmessage()">
        <textarea ng-model="form.message" name="message"
            onkeypress="process(event, this)"
            id="text" class="form-control send-message" rows="3"
            placeholder="Write a reply...">
        </textarea>

    </div>

    <span class="col-lg-3 btn btn-file send-message-btn">
        <i class="glyphicon glyphicon-paperclip"></i>Add Files
        <input ng-model="form.userfile" id="itemImage"
            name="userfile" type="file">
    </span>

    <button ng-click="sendmessage()" id="send"
         class="col-lg-4 text-right btn send-message-btn pull-right" 
         type="button" role="button">
       <i class="fa fa-plus"></i> Send Message
    </button>
    <div id="dvPreview" class="text-center"></div>
    </form>
</div>

Angular:

$scope.sendmessage = function (){
        var formData = $scope.form;
        var friendid = $scope.friendid;
        var req =
            {
                type: 'POST',
                enctype: 'multipart/form-data',
                data:formData,
                url: "<?php echo base_url() ?>User/sendmessages/"+friendid,
                headers: {
                    'Content-Type': 'application/json'
                },

            };
        $http(req).then(function (response) {
            $('#text').val('');
            console.log(response)
        }, function (response) {

        });
    };

here is what i have done before please help.

回答1:

ngModel directive is not usable on file input.

If you don't care about being in debugInfoEnabled on prod, you can pass it true like this in your app.js.

$compileProvider.debugInfoEnabled(true);

You then will be able to access your scope from your html. In you file input just add :

onchange="angular.element(this).scope().yourChangeFunction(this)

You can access your file in your js code with :

scope.yourChangeFunction = function(element){scope.file=element.files[0];}