1

I am writing a line-of-business application in Angular, and I have come across a scenario I can't quite find a nice solution to.

I want to show a banner stating that a user has unsaved changes, and that he can save them. So in my index.html, I have the following markup (using bootstrap):

<div class="alert alert-info" role="alert" style="margin: 20px;">
    <button class="btn btn-info" ng-click="<CurrentController.Save()>" ng-show="<HasChanges>">Save</button>
    <span>You have unsaved changes. Use the button here to save them.</span>
</div>

Now, I have a controller for my current view, and a global appController.

Using prototypical inheritance, my controllers contain functionality to track changes a user makes, and is able to perform whatever actions are necessary to achieve my desired functionality.

My question is:

Since my rootScope does not know about the child controllers, what do I need to do to be able to bind ng-click and ng-show in my above code. In other words, how will index.html know about the currently active controller?

I thought about broadcast/emit, but somehow that just doesn't seem pure to me. I also though about having the child controllers 'register' themselves with the $rootScope, but that could cause my to save in old controllers if I introduce errors.

What is the best practice for this? Is there something fundamentally wrong with my design?

Troels Larsen
  • 4,462
  • 2
  • 34
  • 54
  • broadcast/emit is much cleaner than wrangling potentially deep prototypical inheritances. Inheritance also means coupling data structures of each controller. The global save button should just broadcast an event that each individual controller can react to as they see fit. – user2943490 Dec 04 '14 at 02:54
  • @user2943490: But how would you propagate whether or not the controller is dirty? I don't mind emit per say. Without controller inheritance, where would I place code that is common for all my controllers? – Troels Larsen Dec 04 '14 at 06:49
  • if you have common controller code, a mixin is generally the cleaner pattern. See http://stackoverflow.com/questions/16539999/angular-extending-controller – user2943490 Dec 04 '14 at 08:21

1 Answers1

-1

$dirty of any form would tell you whether the form is dirty or not

in the form controller you can watch for any form changes and store a boolean value in a service, remember to clear the watch as soon as you know the form is dirty

$locationChangeStart is fired when the user tries to navigate to another view

inject the service in $locationChangeStart event and check to see if the boolean value is true of false.

Please ensure you clear the boolean value to false or undefined when the $locationChangeSuccess