I have a site using PJAX all over the place and I have a few pages that are using AngularJS. For the AngularJS pages I would like to continue to use PJAX to get all the benefits associated with not reloading the entire HTML page, assets etc. Unfortunately, PJAX just loads some HTML into the page and doesn't fire any javascript. This is okay, because I can fire the javascript manually on pjax success, but I can't quite figure out what makes AngularJS initialize.
For a simple scenario, lets say I AJAX the following HTML into a page. Also assume, the page already had Angular.js included. What could I call to have the following behave like an Angular App?
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
Thanks
angular.bootstrap(...)
didn't quit work for me, it was throwing an
Already existing App Error.
So I went for the (re)$compile
solution, but the docs are sparse when it comes to using angular from outside the framework (e.g how do you call $compile). After a lot of trial & error this works for me although there might be some overhead :
// outside of angular...
var ngRefresh = function() {
var scope = angular.element("body").scope();
var compile = angular.element("body").injector().get('$compile');
compile($("body").contents())(scope);
scope.$apply();
}
// PJAX
$('#page').on('pjax:success', function(e){
ngRefresh();
});
Manual Initialize worked just fine
angular.element(document).ready(function() {
angular.bootstrap(document);
});
I ended up having some issues with the gem rack-pjax because it was escaping the mustaches in my urls, so I just got rid of the middle ware and decided to have the web server detect the pjax in the request and opt-out of a rendering the layout.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With