#A - watch Pristine form state
HTML
<script src="https://code.angularjs.org/1.2.1/angular-route.js"></script>
<div ng-app="app">
<p><a href="/form">form</a>, <a href="/another">another</a>
</p>
<div ng-view=""></div>
</div>
CSS
form {
padding: 4px;
}
form.ng-dirty {
background: #edc;
}
JavaScript
angular.module('app', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/another', {
template: 'Another page'
})
.when('/form', {
template: [
'<form name="someForm" unsaved-collection="some">',
' name: <input type="text" ng-model="some.name" /> <br />',
' surname: <input type="text" ng-model="some.surname" /> <br />',
' foo: <input type="text" ng-model="some.foo" />',
' <button ng-click="setPristine()">is form should be saved?</button>',
'</form>'
].join(''),
controller: 'ctrl'
}).otherwise({
redirectTo: '/form'
});
})
.controller('ctrl', function ($scope) {
$scope.some = {
name: 'foo',
surname: '',
foo: 'bar'
};
})
.directive('unsavedCollection', function ($window) {
return {
require: '^form',
restrict: 'A',
link: function (scope, element, attrs, ngModelController) {
var collection = attrs.unsavedCollection;
var initial = angular.copy(scope[collection]);
scope.setPristine = function () {
$window.alert(formShouldBeSaved(scope[collection]));
};
scope.$watchCollection('some', function (newVal, oldValue) {
if (newVal !== oldValue && !formShouldBeSaved()) {
ngModelController.$setPristine();
}
});
scope.$on('$locationChangeStart', function (event) {
var answer;
if (formShouldBeSaved()) {
answer = confirm("Are you sure you want to leave this page?");
if (!answer) {
event.preventDefault();
}
}
});
function formShouldBeSaved() {
return...