Tuesday, 15 September 2015

ruby on rails - Using angularjs with turbolinks -



ruby on rails - Using angularjs with turbolinks -

i trying utilize angularjs framework in app turbolinks. after page alter not initialize new eventlisteners. way create work? in advance!

angularjs vs. turbolinks

turbolinks anguluarjs can both used create web application respond faster, in sense in response user interaction happens on web page without reloading , rerendering whole page.

they differ in next regard:

angularjs helps build rich client-side application, write lot of javascript code runs on client machine. code makes site interactive user. communicates server-side backend, i.e. rails app, using json api.

turbolinks, on other hand, helps to create site interactive without requiring code javascript. allows stick ruby/rails code run on server-side , still, "magically", utilize ajax replace, , hence rerender, parts of page have changed.

where turbolinks strong in allowing utilize powerful ajax mechanism without doing hand , code ruby/rails, there might come stage, application grows, integrate javascript framework such angularjs.

especially in intermedium stage, successively integrate angularjs application, 1 component @ time, can create sense run angular js , turbolinks together.

how utilize angularjs , turbolinks together use callback manually bootstrap angular

in angular code, have line defining application module, this:

# app/assets/javascripts/angular-app.js.coffee # without turbolinks @app = angular.module("yourapplication", ["ngresource"])

this code run when page loaded. since turbolinks replaces part of page , prevents entire page load, have create sure, angular application initialized ("bootstrapped"), after such partial reloads done turbolinks. thus, replace above module declaration next code:

# app/assets/javascripts/angular-app.js.coffee # turbolinks @app = angular.module("yourapplication", ["ngresource"]) $(document).on('ready page:load', -> angular.bootstrap(document, ['yourapplication']) ) don't bootstrap automatically

you see in tutorials how bootstrap angular app automatically using ng-app attribute in html code.

<!-- app/views/layouts/my_layout.html.erb --> <!-- without turbolinks --> <html ng-app="yourapplication"> ...

but using mechanism manual bootstrap shown above cause application bootstrap twice and, therefore, brake application.

thus, remove ng-app attribute:

<!-- app/views/layouts/my_layout.html.erb --> <!-- turbolinks --> <html> ... further reading angularjs bootstrapping: http://docs.angularjs.org/guide/bootstrap railscasts on turbolinks (explains callbacks): http://railscasts.com/episodes/390-turbolinks

ruby-on-rails angularjs turbolinks

No comments:

Post a Comment