2

I have a table of settings (e.g., check boxes) on a form and the user has the ability to add and remove table rows. theForm.$dirty gets set if the user changes a setting (e.g., checks or unchecks a check box) but not if a row is added to or removed from the table. I have an example at https://plnkr.co/edit/sOXFnZjpkrcExvxGsEVg

I'm a relatively new Angular developer but I've been cautioned that it is not a best practice to reference $scope if one can avoid it. I think that in this case, I could make the controller depend on $scope then invoke $scope.theForm.$setDirty() in the functions which modify the table. I'm not sure if that is my only recourse or if there's a better approach.

Chris Nelson
  • 3,519
  • 7
  • 40
  • 51
  • can't view your plnkr atm, but what is the reason you want to know if the form is dirty? – TSmith Mar 02 '17 at 16:00
  • One immediate use is to enable or disable a Save button. – Chris Nelson Mar 02 '17 at 16:21
  • makes sense. The accepted answer does what you need (keeps $scope out of the controller), but you asked if there is a 'better' approach. You may consider thinking about asking if your model is dirty instead of/in addition to asking if your form is dirty. I assume your table DOM is driven by some sort of model collection (ng-repeat over a collection). If so, you could also bind a controller method (isModelDirty) to ng-disabled and ask if your model collection has changed or not. Just a thought... – TSmith Mar 02 '17 at 16:35

1 Answers1

3

Just put form to controller:

form name="vm.testForm"

But there is nothing bad if controller depends on scope.

Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
  • 1
    If you plan on migrating to angular 2 or 4, then it's best to get out of using $scope. At least that's what initial reading led me to believe. – jusopi Mar 02 '17 at 15:39
  • Putting the controller name in the `name` of the form (adding `vm.` at the start) does what I want. Thanks, Petr! – Chris Nelson Mar 02 '17 at 16:23