#405 AngularJS pro
AngularJS is an awesome framework for easily creating rich, client-side applications. Its powerful bindings allow you to do a lot with very little code. Here I show how to integrate Angular with a Rails app.
- Download:
- source code
- mp4
- m4v
- webm
- ogv
Fantastic jump start (as always); mirrors all the lessons I had to learn myself over the last couple weeks.
I highly recommend https://github.com/tpodom/angularjs-rails-resource, especially the nested_urls branch, as an alternative for synchronizing with rails.
I just merged the nested_urls branch to master and released a 0.1.0 version of the gem with that functionality included.
does angularjs-rails-resource replace angularjs-rails or can it be used in addition to it?
I may have answered my own question because I noticed that angularjs-rails-resource only contains resource.js whereas angularjs-rails has bootstrap related files etc -
So I would say both
In fact, because Rails prefers JSON be root wrapped, you need to use this library if you want to have a nice clean controller like Ryan's without heavily customizing ngResource.
Everyone just a note.... In some of the firefox browsers the headers get passed as HTML.
To fix this Ajax issue just respond_with :json, :html
thanks very nice... I think will take this alternative over Backbonejs ... very nice
It's easy to test UI changes with https://teatro.io/
Excellent Railscast, as always!
That said, would anyone be willing to share opinions on when it's appropriate to use these frameworks (Angular, Backbone, etc.) vs. the traditional Rails/AJAX way of doing things? I image the benefit has to be pretty tremendous to undertake the learning curve but it's not apparent to me.
For example, would building the app the traditional way be suboptimal? And why?
I really appreciate the guidance! I'm allocating my excess capacity toward becoming a better Ruby programmer but would be willing to divert resource toward learning a new .js framework if that's a more prudent direction.
This is a fantastic question. As I expressed in a comment below, we've been using AngularJS in production for a couple months now with huge success. However, we didn't start off using Angular--at first, we used a more "traditional" (one might say "old school") style of basic, imperative jQuery code.
While this worked, as the application's complexity grew over time, the JavaScript we had written (which I have come to term "jQuery Soup") became more and more unmaintainable. It became clear that our existing direction was not tenable in the long term; this is when I introduced AngularJS to the team.
Now, we have rewritten significant portions of our application using Angular, and things are going very well. That said, if we had started out using Angular (or another client-side framework like Ember, Knockout, Backbone, and so forth), perhaps we wouldn't have felt the JavaScript pain as early as we did, and would not have to rewrite anything.
On the flip side, sometimes these frameworks can take a bit of time to master--Angular gets a little more complex conceptually when you start getting into providers, directives, child and isolate scopes, etc. While the learning curve has proven worth it to our team now, using plain jQuery in the beginning may have allowed us to get our app out the door faster than learning a new framework like Angular would have.
So, while I would say that learning such a client-side framework is a great idea (I believe every web developer should have some proficiency with at least one), I don't think it's necessary to try to force that kind of architecture on every application you write. You have to make a judgement call and determine for yourself if you think it'll be worth it. I will say, however, that if you believe that your client-side code will grow to be even a little complex, some kind of framework is likely a good idea, and as Ryan has demonstrated so expertly here, Angular makes it really simple to build client-side apps!
Thanks for the great overview
Hi Brandon - Thanks a million for sharing your valuable insight!
I'll keep honing my Ruby skills for now but will definitely dabble with a client-side .js framework (and it seems that AngularJS is like the RoR of these...)
I only have my iPad with me. I opened your learnalist site and while it looks great it seems to be quite glitchy on the iPad. The menu floats about 20% from the top of the screen, it seems to resize every so often, every page seems to freeze and become unresponsive on load or when scrolling. While I see you have an iPad app, it seems to be a recurring theme that more complex sites with loads of bindings (ahem gmail ahem) seem to not work well or at all on tablets and lower performance devices. Something to keep in mind.
Also, can you please give us some examples of client side features learnalist has that would otherwise be messy to implement manually with something like jquery?
Not trying to belittle your website btw, I will be sure to open it from a PC later and I'm sure my experience will be great :)
Thanks for the feedback! The mobile web experience is in flux at the moment, but we do have native iOS apps that are pretty awesome! ;) [Edit: I just notice you already said you knew this. My apologies. :)] (To be fair to Angular, we've had mobile web display bugs long before we introduced Angular.)
The infinite scrolling on the homepage, profile page, and board page is something that is now dead simple to set up, thanks to an infinite scroll directive I wrote. Also, binding site-wide follow and like buttons (and other such things) to a
currentUser
model means a single update in the model updates the view everywhere. Also, admin pages (for staff to manage users, featured content, etc.) have been written in record time.We've also been able to both simplify and boost our client-side test coverage compared to the old code (which had far too much DOM access to test effectively).
Thanks Brandon, that's a really helpful post. Would you have any recommendations on learning JS/CS for a JS Noob that knows Rails/Ruby?
Btw, great site too! I searched for Rails and one of my blog posts showed up :D
Thanks, glad to hear you like the site! As far as learning JavaScript and CSS, I'd take a look at Code School--while they have a monthly membership fee, I feel it is well worth the cost. All their courses are interactive (you actually get to write code that they verify works on their servers during practice sessions), and they cover everything from jQuery basics to CSS3 to CoffeeScript to Backbone and beyond. They even have some really great Rails courses for programmers of all expertise levels.
Thanks Brandon. I have actually done most of the Code School stuff :) Do you have any book recommendations?
AstonJ, as a rails beginner, I've found Master Space and Time with Javascript by Noel Rappin to be an excellent resource on Javascript -- specifically if you're accustomed to rails development.
I'm still on the first book, but looking forward to the next three!
Brandon,
Thanks for the review... Have heard that SEO becomes really difficult with AngularJS... Have you experienced the same with learni.st ? What all strategies did you use to overcome SEO related issues??
Yeah, this can be a problem, and people have come up with some pretty clever ways to combat the issue. In our case, the content we display lends itself well to rendering some very basic data on the server into
noscript
tags, and we are going to experiment with that idea first.Excellent introduction to AngularJS! We've been using it fairly extensively in production (in a Rails app) for a couple months now, and it's definitely helped clean up and speed up our client-side code and development time.
As a group that has put together a production level Angular on Rails app, I was wondering if you could answer a question. For your app, do you have all your logic processed client-side (the Angular way) or do you additionally have endpoints that handle logic server-side in a more traditional Rails manner?
For example, going to "root/entries" accesses the Angular framework but "root/" or "root/users" work via logic initialized in a Rails controller and processed via ERB/HAML.
If the latter, how do you go about setting up the app for this type of behavior?
egghead.io can't open.......
Looking forward to series for AngularJS:
parties
nested_urls
widget
...
Can someone who tried both Backbone and AngularJs give us some insights on the +/- of those two frameworks. I'm actually using Backbone in production, but AngularJs magic seems to attract my attention a lot!
thanks in advance for your replies.
Angular and Backbone differ in a few ways. Backbone is more of a low-level library, where much of the implementation is up to the developer. Angular is a much more opinionated (like Rails) framework, and does a lot more for you out of the box. The big difference though is the data-binding.
Standard BB applications usually involve stamping out templates, and reacting to changes on the model is very much a manual process. Of course there are plugins to simplify this like Derick Bailey's backbone.modelbinding.
With angular, the emphasis is on enhancing HTML through directives - which allow you to bind your data (javascript objects and such) to the DOM. This is an immensely powerful concept, because you don't have to deal with listening for events or do DOM traversal. In turn, you can move much of your view logic into controllers which take care of gluing together the interactions. They are somewhat analogous to view models, which should be familiar to anyone who's worked with Knockout.js.
Thanks for this great overview! As someone who's worked with BackboneJS, the dependency injection approach is a clever way of handling complex resource requirements that could crop up over time.
I've been using Angular for 6mos. now and im still amazed by its cleverness (module,DI, directives etc.).. IMO Backbone is past, Angular is the future of client-side webdev.. what Ember?
AngularJS doesn't work with Turbolinks. So if you are going for a non-single-page site you will have to disable Turbolinks. Angular registers alot of eventlisteners on the window and other stuff. It gets thrashed when you swap pages. Alternatively you could implement turbolinks in angular. It shouldn't be too difficult.
Are you sure? I used Turbolinks with another, similar framework - KnockoutJS - and it all worked OK. But if somebody want to build singe page sit it does not need to use Turbolinks.
Are you sure? I use pjax with Rails 3.1 and have a chat (like facebook) with angularJS... everthing just works.
I am using pjax also with my rails application ,I am doing simple social network ,can u provide my with ur code or hints how can I implement chat app on my site ,,I am an expert rails developer and intermediate javascript ,,your help is really valuable for me
and in your opinion ,,which framework is the best for rails application , Ember ,angular ,backbone ,for chat application for example
For me, AngularJS is perfect, everything just works with few code (I tried backbone, ember, pure jquery... and I didnt like anyone for this case).
I have a social network too, but I use angularJS just to chat... everything else is rails with pjax that I think is a better solution to this kind of webapp.
I use memcache (A LOT), my social network is below to 100ms per request, with more than 1,000 online users.
My chat uses nodejs on server, and it support xmpp/jabber as well. It is 50% socket.io and 50% node-xmpp.
Maybe, I'll opening it source. I dont know yet.
if you want, add me on gtalk: maxguzenski@gmail.com
thanks a lot of your help ,,It will be y pleasure to contact you
Maybe Turbolinks is replacing your ng-app tag. If it is the case, you have to rebind angular with "angular.bootstrap(element[, modules]);"
This worked for me: http://stackoverflow.com/questions/14797935/using-angularjs-with-turbolinks
Something for Show Notes:
AngularJS Batarang - AngularJS WebInspector Extension for Chrome
AngularJS YouTube channel, e.g. "AngularJS MTV Meetup: Best Practices"
Awesome RailsCast!
I've been using angular for about 5 months now and it's been a great experience.
Personally I prefer it over Backbone and Ember, both of which I attempted to learn before I discovered AngularJS.
With Backbone, it seemed like I had to write a ton of boilerplate code to get anything working, and my code would get cluttered quickly.
After attempting Backbone, I tried to go with Ember. However, it seemed like it was under such heavy development, that finding good(current) tutorials/documentation was very difficult, which is important to anyone who is starting out to learn something new.
Very interesting episode.. Was giving out AngularJS a try and wanted to understand few things..
So now when I go to forums/1 , I expected it would trigger show action, but it did not. It went to Index action.. How to pass routeParams to query()?
Also, I see that https://github.com/ludicast/angular-rails gem takes a totally different approach... Creating a very different directory structure under app/assets/angular/
controllers/
filters/
services/
widgets/
And all view logic is stuffed into /templates
Which would be more recommended? Anyone have tried out that gem...
I think what you are looking for is setting up routes. In order to be able to use routeParams in your controller, you must first set up routes. There is good documentation for setting up routes here: http://docs.angularjs.org/tutorial/step_07
When you are finished setting up routes, you can then use routeParams in your controller. There is an angular service called $routeParams, which you can pass in just like the other 2 services($scope and $resource).
Ex:
Note: When you want to retrieve a single record, Topic.query() won't work, you must use Topic.get({id: my_id_here})
Ex:
In the angularjs documentation you can find another example of this: http://docs.angularjs.org/tutorial/step_11
and more about using $resource here:
http://docs.angularjs.org/api/ngResource.$resource
I have yet to learn one of these framework (which I want to), but one thing I find odd is that in almost every tutorial or even the docs, it emphasizes "for a single page app".
When was the last time you ever made a single page app? What does that even mean? My apps span many many many pages, and could hardly be seen as some kind of single page calendar or todo list or something.
What am I missing here?
Maybe i don´t understand your question, but why should Angular (or another framework) limit your app to a single page?
I think docs start with minimalistic (single page) examples to give you an understanding of how it works, but that doesn´t mean you have to stay at that level.
I would hope it wouldnt limit it. But it goes beyond just a 'hint'.. i mean a lot of places i read it pretty explicitly says "for one page applications". And ive seen it written more than just here or there. It's pretty much every where I look
I was thinking about this also. The happiest spot for me would be to consider my app as a set of single page apps. Each one would greatly lighten the page reloading, and user experience, but make it easy to move to another single page. The pages would map to my primary resources.
There is often a distinction made when discussing this topic that separates "web applications" and "web sites." The difference is, perhaps, a bit pedantic, but thinking about it in this way can help understand where people are coming from.
For example, Gmail would be a "single page app"--there are no page reloads, and all the content changes are handled via JavaScript. Generally your server software will only render a single view, and the client-side technology will handle moving things around.
A site like StackOverflow, however, would be classified as a "web site" (even though many might call it a web application). While it has elements that lean on JavaScript and Ajax, you still primarily browse content by browsing different URLs, which the server software renders separately.
Client-side frameworks like Angular provide special tools for building the former (Gmail-style) web applications (for example, see Angular's
$routeProvider
service andngView
directive), and people often focus on this because these apps can be harder to write and seem "newer" or "cooler," but Angular can be used to drive elements in a more traditionally built web site as well.I see, that makes a lot more sense, but still, funnily enough I still cant think of many apps I use that are 'single page' aside from gmail. Most apps I like seem more like websites, and model stack overflow more.
I'm sure angular would work fine for a 'website' (as you put it) but are there any JS frameworks more intended for websites rather than one page apps?
I think that you are getting stuck on the "literal" interpretation of a "single page" app. Instead think about the Rich client apps that we have been developing for the past 20 years using clients such as VB PowerBuilder etc. for client/server applications. A single page app is more akin to these Rich Client interfaces of the past years. It does not mean that "multiple" single page app(lets) cannot be bound together to create one "holistic" application. In fact, they have already implemented the Twitter Bootstrap UI widgets in Angular so it is a matter of stitching together many single page angular app(lets) using the UI elements such as tabs, forms, pop-ups, etc.
+1
It isn't just for single page apps. You can put ng-app anywhere so one single widget on the page could use Angular.
If your needs are grand (one-page app), it works. If you just need a small widget/form, it works.
If I have model of User with first_name and last_name and I would use Angular with Rails. I would update User profile on the page on the fly and I would communicate with Rails in background. How should I do validation if model is being submitted attribute by attribute ?
Here is more information on validation: http://docs.angularjs.org/guide/forms.
I HIGHLY suggest validating on the client and backend to cover your bases.
One thing i wonder every time i fiddle around with (MVC-)JavaScript frameworks is how to do this the unobtrusive way – what if i want my app still to work without JS, and what about search engines?
One solution i could imagine are some kind of templates, which replace the "static" versions of my views via JS and then Angular (or whatever) does its job.
How do you solve this? Or is unobtrusive JS oldschool? ;-)
I've had some luck placing angular "apps" into separate partials that can be accessed as templates by AngularJS. If Rails renders server side, real data is used. If angular requests the "partial" via Ajax, I give it sample data that is removed when Angular binds to the template.
This tutorial lays out this concept http://blog.berylliumwork.com/2012/09/tutorials-on-angularjs-and-rails-2.html
Nice episode! Will definitely check out Angular. I was focused on getting up to speed with ember, but this looks great too.
I would probably still hesitate to use any of these javascript frameworks in a consumer facing app though, at least one where I need SEO. But looks like they could be used very effectively for "dashboardy" stuff. Also, the clients have to download all the js before anything can start, and this might slow down the initial startup of your app.
SEO is one of the biggest problems with single page apps and goes back to Flash days as well. Even angularjs.org has bad SEO. They are working on solutions though but this is a global SE issue, not Angular specific.
It is definitely something to consider when choosing the tech for your project.
i believe it's now SEOable with the use hashbang
You seem to keep improving all the time Ryan
we need a vote button here to give you some stats ;).
For now just take this high praise please:
+42
Been learning Angular for the last 2 weeks and it is nice to see a rails specific run through. Now do another one on Angularjs :)
good intro. please do one more screencast covering more aspects of angular
+1... Also I'm waiting for an EmberJS episode ;) would be really awesome
For EmberJS there is a great PeepCode screencast: https://peepcode.com/products/emberjs
It covers the latest version of Emberjs and is IMO worth the 12$.
Migrating from Ember.js to AngularJS ;)
Is it just me, or AngularJS looks so a bad idea? Ryan, don't get me wrong, the episode was great, but I'm not convinced by the framework.
All that
ng-show
,ng-repeat
,ng-class
are looking like the old Java's JSF, and similar frameworks. It also enforces obtrusive JS withng-submit
andng-click
.So my point is: your view will easily become cluttered and totally dependent on it. The advantage of other frameworks like Backbone, is to have a separation of concerns between the presentation and the behavior (less or no dependencies), and a structured client side application (MVVM).
You are so right! If you look at ATG Dynamo (acquired by Oracle), you will see a striking resemblance. It is a matter of personal preference really :)
The AngularJS guys already answered that one: http://blog.ricodigo.com/blog/2012/10/14/announcing-the-release-of-angularjs-scaffold/#comment-686036118
Copy/pasta:
"wrt
ng-click=”archive()” which is mixing html with app logic
- where is the logic? it's archive is just a hook to the controller which defines the logic.For years we've been told about unobtrusive JavaScript and what we ended up with was spaghetti code with unclear relationships between the template and event handlers.
I'm absolutely against logic in the templates, but we have to distinguish between the actual code that represents the business logic and a hook that calls a routine with the business logic."
I very much agree with Patrick's comment, but here's another way to think about it:
In a framework like Backbone, you'd have something like the following code (taken from the Backbone website, minus a few lines):
In this object which is a view, you are setting up event handlers on various elements. These event handlers call functions on the view object, which delegate to models. You also set up callbacks on various model events (such as
change
) which in turn call functions on the view object to update the view accordingly.In Angular, the DOM is your view. When using
ng-click
,ng-submit
, etc., you are setting up event handlers on these elements, which call functions that should delegate to model objects. When usingng-show
,ng-repeat
, etc. you are setting up callbacks on model events that change the view.The fact that AngularJS sets up these callbacks behind the scenes for you is irrelevant; the only difference between this and something like Backbone is that Angular lets you write your view declaratively--you describe what your view is--rather than imperatively--describing what your view does.
So, in in the end,
<a ng-click="model.set({selected: true})">
really adds no more dependencies than...but it sure is a hell of a lot less code. ;)
Thanks Brandon. This is an excellent explanation. Could you provide more details on how to "debug" an application that is using Angular.js? In the Backbone app., I just put a debugger statement where I need to and examine the code variables etc. in the debugger.
Can you elaborate on that a bit?
Bharat
Sure. There are a few ways to debug your code. With imperative business logic (usually contained inside services), you can still use
debugger
and step through the code. DOM manipulation and scope binding are done through things called directives (ng-click
etc. are all directives), so you can put a debugger in your directives' code and step through it as well.For view related debugging, you can get access to scopes (which Angular stores on DOM elements) via
angular.element([DOM Element]).scope()
; there is also a good Chrome extenion called AngularJS Batarang that can help you see the scopes attached to the DOM, and also help you do profiling regarding slow$watch
es ($watch
is the mechanism through which Angular does dirty tracking and automatic view updating).Yeah, that is a really great explanation. Thanks.
"In Angular, the DOM is your view."
I think this is the same mistake that Rails did since its beginning: mixing up the concepts. Instead, the DOM is a template, the view is an object which is responsible for the presentation of a model (see BackboneJS or Mustache).
Agreed. For me, writing ng stuff on html template looks the same as writing Ruby code in erb. I'm okay with attributes and very simple logic such as "if" and iterator. But, no, thanks, no fancy stuff, no functions, I can't bare with them there.
I don't really care if it is a lot less code. Using Backbone creates much more readable and extensible code that is a requires a lot less clutter in the markup.
Angular seems like a great tool, but feel like I would have a hell of a time coming back months after I wrote it trying to tease apart the js and the markup, let alone doing the same if someone else wrote it. I like to keep my markup super clean.
Agree! I don't like cluttered views. I feel Backbone is a more elegant and unobtrusive solution.
You are so right, I have tried AngularJS in the past and it's obstrusive if you want the two way data binding with Backbone use rivets.js, you can check an example I have done http://boriscy.github.com/backbone-rivetsjs/
Hey Ryan,
You should continue with Angular JS screencasts to build a non-trivial application and then repeat the process with Ember JS. That will give us a good frame of reference. Your Backbone screencasts have been very useful to me in coming up to speed.
Just a suggestion.
Keep up the good work.
+1
+1
+1 I was actually a bit surprised to see an angular screencast before an ember screencast.
+1
Ryan, excellent as always!
I would REALLY like how integration with a testing framework. In particular, how to test interaction with the server, e.g. interaction requires login, and test verifies response from server.
Er, that should have been "I would REALLY like to see how integration with a testing framework can be done." :$
Here is my small opensource project written in angularjs https://github.com/lucassus/mongo_browser I think it could be a good starting point for anyone interested in combining ruby apps with this awesome js framework ;)
Example of how to not populate the global name space using Angularjs and Coffeescript.
And, how do you $inject the dependencies to be able to minified your angular.js?
According to the doc you have to
MainCtrl.$inject($scope, $http)
for it to properly minify your js assets in production.
That's one option, the other is to pass the arguments as strings in the array as shown in Nick's example. His example will minify properly.
Episode 404 is missing, great joke!
:)
Hah!
Excellent cast, I can definitely see how the jQuery soup I currently have can be moved into AngularJS. And 404 not found - very funny.
I've released angularjs_scaffold to help you develop your app with angularjs and rails (it generates angular's models, controllers and views) https://github.com/patcito/angularjs_scaffold
No I18n yet.
Thank you Ryan. This is really amazing screencast.
I have been seeing the lots of JavaScript frameworks on the planet. How can we determine the correct JavaScript framework?
[Angular|Knockout|Backbone|Active|Sammy|Raphael|Node].JS
Which is the best solution for specific applications as i expected to use with Rails?
I assume that Angular is a good starting point. :)
See TodoMVC to help you decide.
Thank you Travis for this information. TodoMVC will help me, i assume, in the near feature.
There is another one, JS MVC framework for Rails - Joosy. And Node.js is not a client side framework. It's the server side framework.
Thanks Jaroslaw for the quick but important tip about Node.Js I want to look at Joosy too.
Rails is a great anchor for working with any kind of JS MVC Framework. Through the use of the Asset Pipeline, JSON Generation gems like Rabl covered in this Railscasts and even gems like Gon also covered here along with the myriad of gems for use with JS templating (like ECO) you get the benefit of turning Rails into an amazingly streamlined API, built to support rich client side applications.
There isn't really an answer to the "correct" nor the "best" JS MVC Framework to use. I've personally built a large scale application (700+ JS files) using Backbone alongside Marionette. It's been awesome. There is a critical lack of sites dedicated to showing real world applications built leveraging these frameworks with Rails. Anyway I know this is an Angular episode, but I figured I'd point out BackboneRails.com because it can give you insight into the Backbone world of building apps with Rails, and can maybe help you make the decision that's best for your app. :-)
Check that one ;) http://durandaljs.com/
DurandalJS vs. AngularJS
Any comments on
Meteor
? is it still far from a JS framework for production?Great Cast!
FYI, Bootstrap components written in pure AngularJS:
http://angular-ui.github.com/bootstrap/
I did a slight variation of this project, and I was able to create new records (that persisted), the only problem is that now I pushed the app to heroku, records no longer persist.
It was working fine locally, so either it has something to do with precompiled assets, or there's some strange discrepancy when switching from sqlite to postgres.
Link to Repo:
https://github.com/lukethomas14/Angular-Todo
Link to App Deployed on Heroku:
http://angularfun.herokuapp.com/
The problem is that rails asset pipeline will minify your javascript and rename variable names. So you need to pass arguments as strings in the array:
@App = angular.module("App", ['ui', 'ngCookies', 'ngResource']).config(["$routeProvider", ($routeProvider) ->
or you can modify your environment config to not mangle the variables when minimizing. I modified the code to "do the right thing" and worked fine for me on Heroku. Happy to help.
Thx for this episode. Where is part 2? :)
I think this episode needs a part 2 or maybe part 3 episode since most rails apps are more complex. Would be great to have a proof of concept for a website with different pages, authentication, authorization.
Have a nice day.
Definitely a part 2 worth!!
As always. I'm looking at angularJS because I have to rewrite something.
Let's check out Railscasts... BÄM.. Tutorial for exactly that.
Mindreader.
Cheers
Btw... I got stuck how to use https://github.com/mikepinde/angular-ui-rails
on my angularJS application. I want to handle keypress event with it, but after I follow the steps in some tutorial (blog), it seems not worked. anyone can give me some good tutorial for "how to use angular-ui-rails"?
Cheers
btw.. solved.
Please fix the code markup, I see bunch of 'quot;'
I just took a look at the ASCIIcast and the show notes, it looks like someone has corrected this already.
Excelent article: AngularJS for jQuery Developers
Railscasts make me more and more sad lately: boring js-frameworks reviews instead of hardcore rails features.
It's time for be renamed to jscasts.
Ryan shows very nice how to integrate js-frameworks into Rails. Thats very helpful.
Thanks for this. It'd be great to see a RailsCast or two on Backbone Marionette.
Have a look at http://www.backbonerails.com/
Hi Ryan,
Thanks for the frontend framework episodes!
In the EmberJs app there was one feature not included in the AngularJs app - disabling the button if all entries are winners.
I implemented that in Angular easily by using ng-disabled="allWinners()" on the button and controller code
however I noticed that it was being called a lot (4 times on load and everytime a character is entered in the textbox).
Is there a way in Angular to only call a bound function when a property is updated, much like Ember does?
Hello everybody,
My questions:
Thanks for any help guys.
Kurt
resource has controller
Thanks for all the railscasts.
I have been thinking to change an existing app of mine to a single page app. Planning to use either backbone, angular or ember. Saw the railscasts on all three of them and I understood how to get them to rails.
I am sure that each of these have their own pros and cons depending on the situation. It would really be nice if you have a railscast that can elaborate on the situations where one them would be better than others.
I tried angularjs_scaffold as mentioned at the end of the video. But I see it's version of angular is 1.03 and seems like not much is happening on their github account either.
angularjs_scaffold github
The approach you used in this video is nice for a 1 page app but just wondering how it would scale for a full site with numerous apps or features which is why I tried angularjs_scaffold.
Do you think angularjs_scaffold is still viable? And is the method in this tutorial good enough to build a full angular website.
What I mean by full website is that as with angularjs_scaffold, other than the welcome page, all the controllers output json and all the views are basically being managed by angular.
Thanks for the great vids!
Al
Has anyone seen or created a solid example of using delete? Or even better, batch delete? Say I want to clear all entries in the example...I'm trying to use a simple call to a $scope.clearEntries function in my raffle.js.coffee file but doesn't seem to work.
Great kick off for Angular as always though, Ryan. Thanks again.
I did:
Then pass in the $index parameter when delete function is called:
delete function:
Sweet. will take a look. thanks man!
so I have that working for individual records and thanks for that. What if I want to delete all entries? Thoughts?
I tried this which seems straightforward but no joy:
Does anybody have an example of extending this example with at least one more controller?
I tried to add more entities. After I add more entities, I tries to add data and I got 422 status. And this is my code:
Can I use this way?
Vide: Ember vs Angular
Can't verify CSRF token authenticity
https://github.com/xrd/ng-rails-csrf
This worked for me...
Thanks Man! This is what I was looking for one of my projects... :)
Cage Match - EmberJS vs. Angular http://vimeo.com/68215606
On Rails4, this didn't work for me in
config/environment/production.rb
:but this did work:
Thank you for posting that! I was getting the error
uninitialized constant Sprockets::LazyCompressor
and couldn't find the answer anywhere else
Hi Ryan,
I liked this episode but would really like to see how one would approach the has_many model situation and nested forms with angularJs. I cant find anything that can help me save the attributes from one model plus the nested model.
Hello, Jason
To have access to your models in Angular you have to do:
1. Declare your model in rails .rb file (hope you've done with this)
2. Declare model as resource in route.rb (resources :your_model )
3. Pack it to JSON in Rails Controller
4. Create angular factory with next code
angular.module('GarageCRM.resources').factory 'Your_model', ($resource) ->
$resource 'your_model'
That's all. After configuring angular routes (it's pretty simple) you'll have access to any nested model or attribute.
This should help coderberry.me
p.3 in this case should look like (here tags, etc. have polymorphic relations) :
class OrganizationsController < ApplicationController
def index
@organizations = Organization.all
respond_to do |format|
format.json { render :json => @organizations.to_json( :include => [:user, :tags, :emails, :phones] ) }
end
end
end
That's way angular will bind all of your nested attributes
I want to know if someone do some angular unit test with karma or something else ?
It hard to find something on the web when i use 'rails coffeescript angular test'
i found almost nothing ...
checkout http://joshdmiller.github.io/ng-boilerplate/#/home
it has good examples of how to do tests. It doesn't take much to customize to get to work with something similar to what is suggested in this screencast.
Ignore the rails part
angular does not depend on rails.
just search for angular testing or angular karma tests
Ryan. On behalf of all beginners I am begging you PLEASE stop using Coffeescript. It is hard enough that we have rush to master several techniques simultaneously, people keep overcomplicating stuff which is already hard enough with things like Coffee. Please!!!
Just wanted to give the opposite feedback, thanks for showing how it is done in Coffee
I second grammakov's request; plain javascript would be more helpful for me.
If you are getting a 406 'unacceptable' when following the tutorial, then make this small change in your $resource in the coffeescript file:
"/entries/:id.json"
The .json makes it acceptable.
Thanks!
Feather,
Thanks so much for pointing this out. I've been searched solutions for hours and finally get rid of that 406 error.
Thanks so much!!
Jay Kan
Thanks mate!
thank you!
Alternatively, set the default format in the routes.rb file:
Thanks !
Great vid mate, however using Rails 4 I'm getting the following error on my create and update methods:
ActiveModel::ForbiddenAttributesError
Not a rails expert, but found the solution for anyone else with the issue. Rails 4 now uses strong params with protecting attributes now done in the controller
Thanks!
Great comments, especially Sergey and Adrian's comments helped me get mine working. I put a clear winner button. Here's the code:
raffler.js.coffee
index.html.rb
I would add
entry.$update()
after "entry.winner = false" to persist the action
I recently wrote an article about how to set up Angular in Rails, making Karma aware of the assets pipeline.
The magic is basically in a rake task:
with the karma configuration being:
More info: http://sebastien.saunier.me/blog/2014/02/04/angular--rails-with-no-fuss.html
Not sure why the creator of this didn't post this, but here is a working version of this episode for Rails 4. https://github.com/nynj/angular-railscasts-rails4 A summary of the differences:
1. Add in strong parameters in the the entries controller
2. add in csrf-tokens in the coffeescript
3. keep jquery in application.js. Not sure why this is needed, but I had to keep jquery in.
Just wanted to thank you for this even after 6 months. My main problem was the data not persisting and I finally looked at the console to see that it was an issue not having csrf-tokens.
Thank you very much for the cast. I've been having trouble with Entry.query(). It gives me an Server Internal Error 500 and does not return the query. If I replace the call with hardcoded list of entries it works. Anyone knows what might me going wrong? thank you
Here is a comparison of different ways to get started making an AngularJS app including the example from this railscast
http://www.dancancro.com/comparison-of-angularjs-application-starters/
Ryan, thanks for this intro. A nicer example would have been in one where you show how angular can help client side validations especially since client side validations is not well maintained.
So all that "complex" logic goes in the js files, and routing is done through angular. Does all of this make the rails functionality for these tasks redundant? How do you resolve or use both simultaneously?
For some reason I never connect to the database. Verified that it was populated withe seed data. However the seed data never displays neither is any input added. Any suggestions?
I had a similar experience, maybe this answer can help you? http://stackoverflow.com/questions/23579808/406-not-acceptable-in-rails-4-with-angularjs
guys
in rails 4.2 not work for me
https://github.com/thiagovsk/raffler_rails_angularjs
I used 'angularjs-rails' gem here. https://github.com/kangkyu/angular-railscasts_405
Did you find any solution on this issue? I am using 4.2.1 and have same error. I am using angularjs-rails gem but no luck.
To anyone who is looking for an easy Rails plus Angular setup, the gem Entangled might help. It's very easy to integrate and is basically ActiveRecord for Angular. It also syncs all changes to your database in real time across all connected clients.
https://github.com/dchacke/entangled
Wonderful! Just what I was looking for! :)
Very nice
Works with :
and :
Using Rails 4.1.7 ; very new angular user.
Thanks for this man!!!