<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/api-check/7.5.5/api-check.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-formly/7.3.0/formly.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-formly-templates-bootstrap/6.1.5/angular-formly-templates-bootstrap.min.js"></script>
    <script>
      var app = angular.module('plnkr', ['formly', 'formlyBootstrap']);
      app.controller('mainController', function($scope) {
          this.model = {};
          this.fields = [{
             key: 'name',
             type: 'input',
             templateOptions: {
               type: 'text',
               label: 'Name',
               required: true
             }
            }];
          this.busy = false;
          
          this.submit = function() {
            this.form1.$setSubmitted();
            return false;
          };
        });
      app.config(['formlyConfigProvider', function(config) {
      	config.extras.errorExistsAndShouldBeVisibleExpression =
      		function (viewValue, modelValue, scope) {
      			var form = scope.form;
      			var fc = scope.fc;
    			  return form.$submitted || fc.$touched;
      		};
      }])
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css" />
  </head>

  <body ng-app="plnkr">
    <div class="container" ng-controller="mainController as vm">
      <h1>Test</h1>

      <h1>Steps to reproduce</h1>
      <ol>
        <li>Leave the name field blank</li>
        <li>Check the busy flag to hide the form</li>
        <li>Un-check the busy flag to display the form</li>
      </ol>
      
      <h1>Expected result</h1>
      <p>The form should contain all its fields and show as invalid</p>
      
      <h1>Actual result</h1>
      <p>vm.form continues to refer to the old form that is now blank.</p>

      <h1>Form</h1>
      <label><input type=checkbox ng-model=vm.busy> Busy</label>
            
      <div ng-if="!vm.busy">
        <form name="vm.form" ng-submit="vm.submit()" novalidate>
          <formly-form form="vm.form" model="vm.model" fields="vm.fields">
            <button type=submit>Submit</button>
          </formly-form>
        </form>
      </div>
      <div ng-if="vm.busy">
        Working...
      </div>

			<span class="label label-success" ng-show="vm.form.$valid">Valid</span>
			<span class="label label-danger" ng-show="vm.form.$invalid">Invalid</span>
      <pre>{{vm.form|json}}</pre>
    </div>
  </body>

</html>