Another title for this post might have been “Using AngularJS with ASP.NET Update Panels” as that was the circumstance I found myself in. However, the method of manually bootstrapping AngularJS framework applies to just about any tight spot you would like to fit in the framework.
The first problem I ran into with this integration was that all my angular markup and content was simply not present on the page on first load. The content itself would show up dynamically after a partial post from the Update Panel. This meant that the default bootstrapping process of Angular will not run as no “ng-app” or HTML is even available to run, and it automatically will not initialize when the update panel adds “ng-app” from the server post. So what to do?
AngularJS actually provides just the thing for this situation, with a special “bootstrapping” method:
Yay, for Angular. With this method, I can manually initialize AngularJS in any tricky situation I may find myself in for legacy code. With the scope usage of ng-app as well, I can use Angular on a specific portion of the page only! So to use the bootstrap event, the biggest challenge is finding a spot to make the initialization request. In my scenario, I need to bootstrap right after the partial post returns. I am using a framework that wraps the update panel so I already have an event as follows:
However, this would just as easily work by hooking into the Page Request Manager like the following:
In this example, I declare my application module (as “program”). Then call the bootstrapping angular function and pass in the HTML element that is to represent your ng-app (no need to declare ng-app anywhere in your markup, this takes over for that). In my example, I then pass in my program module, which has reference to all the controllers used in that application. All should work normally from here on out.
For my scenario, I had server side Html Table Generator. So, I created a new directive and added the directive to a div wrapper around the control:
In the above example, you can see the directive as “clickable-table”. This directive takes an attribute argument of “row-click” which is a function that will get called whenever the user clicks on a row in the table. The messy manual manipulation and jQuery usage remains within the directive, and your controller remains clean:
This is a simple example, but you can see how to easily extend it from here. Keep in mind if you end up inside a JQuery event to bring the Angular Scope back into context by manually wrapping the “rowClick” event in a scope.$apply.