StackOverflow_24497834: getting-form-state-from-child-to-parent-controller

Illustration of answer to http://stackoverflow.com/questions/24497834/getting-form-state-from-child-to-parent-controller.

by ExpertSystem

HTML

<script src="https://code.angularjs.org/1.2.18/angular-route.min.js"></script>
<body ng-app="myApp">
<script type="text/ng-template" id="form.html">
  <form name="userForm">
      <input type="email" placeholder="email" ng-model="user.email" required />
      <input type="text" placeholder="name" ng-model="user.name" required />
  </form>
</script>


<div ng-controller="MainCtrl">
  <ul>
    <li><a href="#/new">New User</a></li>
    <li><a href="#/edit">Edit USer</a></li>
    <li>To continue as guest, click on submit</li>
  </ul>
  <ng-view></ng-view>
    <button ng-click="save()" ng-disabled="!buttonConfig.enabled">
        Save and continue
    </button>
</div>
</body>

CSS

input.ng-invalid {
    border: 2px solid red;
}

input.ng-valid {
    border: 2px solid green;
}

JavaScript

var app = angular.module( "myApp", ['ngRoute'] );

app.config( function ( $routeProvider ) {
  $routeProvider
  .when('/edit', {
      templateUrl: "form.html", 
      controller: "EditController"
  })
  .when('/new', {
      templateUrl: "form.html",
      controller: "NewController"
  })
});

// parent controller
app.controller( 'MainCtrl', function ( $scope ) {
    $scope.buttonConfig = {enabled: false};
    $scope.save = function() {
        // Question 1: How to make sure the form is valid
        // and then change contents of ng-view
        // if ($scope.userForm.$valid) {  } - invalid
        
        // Question 2: How to disable save and continue button when the forms are invalid?
    }
});

// child controller
app.controller('NewController', function($scope) {
    $scope.user = {}
    $scope.$watch('userForm.$valid', function (newValue) {
        $scope.buttonConfig.enabled = !!newValue;
    });
});

// child controller
app.controller("EditController", function($scope) {
    $scope.user = {name: "Foo", email: "bar"};
    $scope.$watch('userForm.$valid', function (newValue) {
        $scope.buttonConfig.enabled = !!newValue;
    });
});