SO Service to Synchronize Form State
by Jeremy Likness
HTML
<div ng-app="myApp">
<form name="myForm" ng-controller="myController">
<input type="text" required="" ng-model="text"/>
</form>
<div ng-controller="secondController">
<span ng-show="isValid">Valid</span>
<span ng-hide="isValid">Invalid</span>
</div>
</div>
JavaScript
var app = angular.module("myApp", []);
app.service("formService", function() {
return {
isValid: false
};
});
app.controller("myController", function($scope, formService) {
var _this = this;
this.formService = formService;
this.$scope = $scope;
$scope.$watch("myForm.$valid", function() {
_this.formService.isValid = _this.$scope.myForm.$valid;
});
});
app.controller("secondController", function($scope, formService) {
var _this = this;
this.$scope = $scope;
this.formService = formService;
$scope.isValid = formService.isValid;
$scope.$watch(function() {
return _this.formService.isValid;
}, function() {
_this.$scope.isValid = _this.formService.isValid;
});
});