How can I set a form contained inside a ng-include to be prestine?

后端 未结 4 1122
轻奢々
轻奢々 2021-01-07 23:33

I have the following code:

4条回答
  •  渐次进展
    2021-01-08 00:12

    If you want to achieve this as the result of some user interaction, in my opinion a much more cleaner and 'angular' way of doing it would be to use a custom directive which will set the form to pristine (i.e. when the user wants to clear the form by pressing esc or clicking a button or whatever).

    app.directive("formCleaner",
      function () {
            return {
                restrict: 'E',
                require: '^form',
                scope: {
                    callback: '&',
                    defaultText:'@'
                },
                template: '',
                link: function (scope, element, attrs, formCtrl) {
                    scope.setFormToPristine = function () {
                        formCtrl.$setPristine();
                        scope.callback();
                  };
                }
      };
    });
    

    and simply hook it up to some button in your form:


    And if you're looking to set the form to pristine directly from the controller, (not as a result of some user interaction) such as success response from a POST, then one way would be to assign a callback to the directive which will be responsible for clearing the form and then invoking that callback from the controller. In your view:

    
    

    and the controller:

     $scope.resetFormOnSubmitCallback=function(cb){
        $log.warn("simulating $http POST call.....");
          $timeout(function() {
                cb();
                $scope.someModel=null;
            }, 3000)
      }
    

    and the directive:

    return {
                restrict: 'E',
                require: '^form',
                scope: {
                    callback: '&',
                    defaultText:'@',
                    ngDisabled:'='
                },
                template: '',
    
                link: function (scope, element, attrs, formCtrl) {
                var setFormToPristine=function(){
                  $log.log("setting form to prsitine....");
                  formCtrl.$setPristine();
                };  
    
                    scope.submitForm = function () {
                    scope.callback({
                        onFormSubmittedCallback:setFormToPristine
                    });
                  };
                }
      };
    

    See plunk

提交回复
热议问题