Tracking dirty objects in AngularJS

Tracking if an object is changed or not in AngularJS is quite easy but is also part of the UI so not always completely obvious. If you want to see if there are changes the $scope or the model will not tell you. Instead you need to take a look at the ngForm FormController. It has a $dirty flag that will tell you if an object is dirty or not. Saving that to the model itself is really easy, just use an ngForm directive, and the form element is automatically an ngForm directive, and the FormController will be added to the scope under the name you added, in the example below it is named frm. Next just set up a $watch() and Bob is your uncle :-)


   1: <!DOCTYPE html>

   2: <html>

   3: <head>

   4:     <style>

   5:         [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],

   6:         .ng-cloak, .x-ng-cloak {

   7:             display: none !important;

   8:         }

   9:     </style>

  10: </head>

  11: <body ng-app="app" ng-controller="demoCtrl">

  12:     <form name="frm">

  13:         <input type="text" ng-model="person.firstName" />

  14:         <hr />

  15:         {{person | json}}

  16:     </form>


  18:     <script src="scripts/angular.js"></script>

   2:     <script src="Script1.js">


  19: </body>

  20: </html>


   1: (function (angular) {

   2:     function demoCtrl($scope) {


   4:         $scope.person = {

   5:             firstName:"Maurice"

   6:         };


   8:         $scope.$watch("frm.$dirty", function(newValue) {

   9:             $scope.person.isDirty = $scope.person.isDirty || newValue;

  10:         });

  11:     }


  13:     angular.module("app", [])

  14:         .controller("demoCtrl", demoCtrl);

  15: }(angular));



Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>