Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$dirty not working as expected when the input type is "file"

Am quite new to AngularJS. The issue is i have a form with two fields- name and profile pic as shown in the code below. I am using ng-upload (https://github.com/twilson63/ngUpload). I want the 'Save' button to work only if either field is dirty and the upload isn't happening currently so that multiple post requests are not triggered on the user clicking on the 'Save' button. But looks like, $dirty works fine with the 'name' field but not with the 'profile pic' field. Am i just missing something? How to go about it keeping it as simple as possible for a beginner of AngularJS. Any help would be appreciated.

             //Code
             <form id='picUpload' name='picUpload' ng-upload-before-submit="validate()" method='post' data-ng-upload-loading="submittingForm()" action={{getUrl()}} data-ng-upload='responseCallback(content)' enctype="multipart/form-data">
             <input type="text" name="name" data-ng-model="user.name" maxlength="15" id="user_screen_name" required>
             <input type="file" name="profilePic" data-ng-model="user.profilePic" accept="image/*">
             <div class="form-actions">
        <button type="submit" class="btn primary-btn" id="settings_save" data-ng-disabled="!(picUpload.name.$dirty|| picUpload.profilePic.$dirty) || formUploading">Save changes</button>
    </div>
</form>

             //In my JS code
             $scope.submittingForm = function(){
        $scope.formUploading = true;
             }

Regards!

like image 567
5122014009 Avatar asked Dec 09 '22 10:12

5122014009


2 Answers

I made a directive ng-file-dirty

  .directive('ngFileDirty', function(){
    return {
        require : '^form',
        transclude : true,
        link : function($scope, elm, attrs, formCtrl){
            elm.on('change', function(){
                formCtrl.$setDirty();
                $scope.$apply();
            }); 
        }   
    }   
  })
like image 61
futbolpal Avatar answered Dec 10 '22 23:12

futbolpal


I haven't used ng-upload before, but you can use onchange event of input element. onchange event is fired whenever user selects a file.

<input type="file" onchange="angular.element(this).scope().fileNameChanged(this)" />

Javascript :

var app = angular.module('MainApp', []);
  app.controller('MainCtrl', function($scope)
  {
    $scope.inputContainsFile = false;
    $scope.fileNameChanged = function(element)
    {
        if(element.files.length > 0)
          $scope.inputContainsFile = true;
        else
          $scope.inputContainsFile = false;
    }

  });

So now you can check if inputContainsFile variable is true along with dirty check of name field

like image 39
H Sampat Avatar answered Dec 10 '22 23:12

H Sampat