Angular JS重置自定义指令

时间:2016-04-14 10:30:27

标签: angularjs angularjs-directive

我想在单击清除按钮时重置此指令(清除所选文件)。目前即使单击清除按钮,所选的文件仍然会退出并且不会被清除。

的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;
    };
});

1 个答案:

答案 0 :(得分:1)

通过将其设置为$scope.connectionParams,不确定null是什么,您希望重置该表单。

但是,要实现相同的表单重置逻辑,您可以使用Javascript的内置 reset() 方法,但是,在 Angularized 方式。

为此,您可以为此定义指令:

/* ... */
.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>'
})

并在表单中使用它,如下所示:

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

Demo