I was experimenting with using AngularJS and JQueryMobile together and loading pages dynamically. The page loading and routing can either be handled by JQueryMobile ($.mobile.pageContainer.pagecontainer(“change”,“page_name”)) or AngularJS. With AngularJS you can use $route service along with ngView and/or use ngInclude .
ngInclude looked easy enough to start with, but did not turn out to be that easy. I will take as simple example of a login application. If user is not logged-in, the app will display the login page and after successfully logging in, the application will display the main page, with the option to logout.
Here is index.html –
Body of the page has a JQueryMobile div-page with header, content and footer. The content div calls ng-include directive and source is returned by getTemplate() function, which is declared in angular_app.js.
First I initialize window.loggedIn flag to false. Then declare Angular App and controllers – mainController (used in index.html), loginController (used in login.html) and mainPageController (used in main.html). getTemplate function is declared in the mainController and it returns appropriate page name depending on value of the flag window.loggedIn.
And main.html –
You can see how this application works here – enter user name and password as admin.
The problem is that JQueryMobile styles are not applied to the dynamically included files. You will see that buttons appear as links instead of JQM buttons and text fields are also not JQM text fields.
The solution for this problem is to trigger JQuery Mobile create event on the parent div, in this example it is mainDiv in index.html. So I need to call $(“#mainDiv”).trigger(“create”);
But when and where do I call it from? It has to be called after ng-include is done with loading and compiling the page. So I need to handle $includeContentLoaded, which is triggered when ng-include is done loading the content. This event has to be handled on the AngularJS scope belonging to ng-include directive – in this example it is the scope in mainController because ng-include is within mainDiv and mainController is associated with mainDiv. So I modified mainController as follows –
Notice $scope.$on(“$includeContentLoaded” …), $(“#mainDiv”).trigger(“create”) is called in this event handler. You can see updated application here – notice that buttons and text fields appear properly now.
So important thing to remember is that you need to apply JQueryMobile styles to dynamic pages not loaded using JQueryMobile by triggering create event. And if you are loading such pages using ngInclude then call trigger function of JQueryMobile in the handler for $includeContentLoaded event.