Vimal David
Vimal David

Reputation: 585

Angular JS reset custom directive

I want to reset this directive(clear the file chosen) when clear button is clicked. Currently even though when clear button is clicked , the file chosen is still exits and its not cleared.

test.html

<form class="form form-basic" id="testForm" name="testForm">

      <div class="row">
        <label class="col-md-6 control-label">File :</label>
        <div class="col-md-6">
            <div class="form-group">
                <input type="file" ng-model="test" on-read-file="loadContent($fileContent)" />
            </div>
        </div>
    </div>


    <button class="btn btn-primary" ng-click="clear()">Clear</button>
</div>

directive.js

fileAccessModule.directive('onReadFile', function ($parse) {
return {
    restrict: 'A',
    scope: false,
    link: function (scope, element, attrs) {
        var fn = $parse(attrs.onReadFile);

        element.on('change', function (onChangeEvent) {
            var reader = new FileReader();

            reader.onload = function (onLoadEvent) {
                scope.$apply(function () {
                    fn(scope, {$fileContent: onLoadEvent.target.result});
                });
            };

            reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
        });
    }
};

});

testController.js

    testControllerModule.controller('testController', function ($scope, $log, $location, deviceDetailsService) {
  $scope.clear = function () {
        $scope.connectionParams = null;
    };
$scope.loadContent = function ($fileContent) {
        $scope.connectionParams.privateKey = $fileContent;
    };
});

Upvotes: 0

Views: 3552

Answers (1)

Ahmad Baktash Hayeri
Ahmad Baktash Hayeri

Reputation: 5880

Not sure what $scope.connectionParams is that by setting it to null, you are expecting the form to be reset.

However, to achieve the same form reset logic, you can resort to Javascript's built-in reset() method, but, in an Angularized manner.

To do so, you can define a directive for this as such:

/* ... */
.directive('formReset', function() {
return {
  restrict: 'E',
  replace: true,
  scope: {
    formName: '@'
  },
  link: function(scope, iElement) {
    iElement.on('click', function() {
        var form = document.querySelector('[name="' + scope.formName + '"]');
        form.reset();
      });
    }
  },
  template: '<button type="button">Reset</button>'
})

and, use it in your form as in the following:

<form-reset form-name="yourFormName"></form-reset>

Demo

Upvotes: 1

Related Questions