Adding AngularJS to existing ruby on rails app - ruby-on-rails

I'm thinking about adding AngularJS to an existing app.
The app is an event management app with a dashboard action for each event.
So we have something like http://localhost:3000/events/2/dashboard
We are trying to make the dashboard view more user friendly by adding AngularJS.
The goal is to implement a controller which will retrieve the event id to make calls to other services and populate the results into the view.
I've read about the $routeParams but in most of the case the examples were dealing with single page applications with their own templates.
Is there any clean way to just retrieve the event id param from the url?
Any help would be highly appreciated.

By using the angularUI router you can retrieve the event_id param from the url and you can also have nested views.
angular
.module('paisApp')
.config ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) ->
$urlRouterProvider
.otherwise("/")
# Define 'app' states. The order of the state is important.
$stateProvider
.state "event_dashboard",
parent: "default"
url: "/events/:event_id/dashboard"
views:
"":
controller: "EventsController"
templateUrl: "/assets/events/dashboard.html.erb"
Now in your events controller you can use the following to access the event_id
$stateParams['event_id']

Related

Add a #/ to the start of the url in a controller redirect in Grails 3.2.3

I am building a custom angular app in Grails, but sticking as much as possible to the default Grails Controller View behaviour.
What I'm trying to do is: using the scaffolding controller. Get the same behaviour but by ading a #/ to the start of the url. So that after you save a Record, you'd be redirected to:
http://localhost:8080/#/country/show/5
instead of
http://localhost:8080/country/show/5
So that Angular kicks in again. I know this isn't the standard Angular behaviour but I'm trying to use as few angular files as possible since I have very little knowledge in angular.
The default scaffolding redirect is:
redirect country
And I tried using:
redirect base: "#/", country
redirect country, [base: "#/"]
redirect country, base: "#/"
redirect absolute: "#/", country
But they all throw 500 error when called.
This is my current app config in angular:
app.config(function($routeProvider) {
$routeProvider.when("/:controller/:action",{
templateUrl:function(params){
return '/'+params.controller+'/'+params.action;
}
})
.when("/:controller/:action/:param",{
templateUrl:function(params){
return '/'+params.controller+'/'+params.action+'/'+params.param;
}
});
});
Have you tried this?
class SomeController {
LinkGenerator linkGenerator
def action() {
redirect uri: linkGenerator.link(
controller: 'country', action: 'show', id: 5, base: '/#')
}
}
UPDATE: Given the requirement to support multiple formats, teaching angular to work with "pretty" URLs might be the only way. Here is an example posting that has the following code:
angular.module('scotchy', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : mainController
})
.when('/about', {
templateUrl : 'partials/about.html',
controller : mainController
})
.when('/contact', {
templateUrl : 'partials/contact.html',
controller : mainController
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
});
I ended up giving up on angular entirely. To show the views inside a dialog I just extract the html segment from the response returned from the server and I get all the default behaviour that Grails includes out of the box.
Since grails is a full stack framework and it's front end is highly customizable. Unless you want to build an entire angular app it's not worth replacing the front end with angular just for it's single view capabilities.
The server responses may be slightly bigger than what I need to show inside a dialog, but it doesn't hurt performance. And the controllers don't know if their views are being rendered inside a dialog or as a full web page, which is what I wanted in the first place.

using angular router in custom pages

I have a rails app with dashboard page. So the page will be http://mywebsite.com/dashboard. It has few links available which will load pages via ajax and show it in a div section inside the dashboard page. Its all working fine. So lets assume I want to use angular here and I specify code like below.
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html"
})
})
My doubt is that:
So in here if dashboard is the root url then the url generated is http://mywebsite.com/#route1
What if my dashboard page is defined like this
http://mywebsite.com/dashboard and I want to define route like http://mywebsite.com/dashboard/#route1
Note: Its not a single page application. But I want the dashboard page
to be like a single page one..
This will work fine and the route will be relative to your URL
http://mywebsite.com/dashboard.
If you were using HTML5 mode with Angular UI router if you try and interoperate the full URL. But because you are not using HTML5 mode, Angular UI router routes using #.

Multipage SPAs with AngularJS & Rails using ui-router

I have a Rails application in which I am trying to replace some views with AngularJS, but not all. In each view I replace, I want it to basically act as if it is it's own SPA. I am also trying to use ui-router to manage states within each of these SPAs.
For example, I have a Rails route that maps to a view ".../checkout/1. This triggers a Rails view in which I load the initial SPA for the flow and then let angular take over. I would like to setup ui-router states that are just specific to this checkout flow.
Where I am getting stuck is how to have states that are only specific for that flow with that base url. If I setup the states:
$stateProvider
.state('start', {
url: "/",
templateUrl: "..."
})
.state('route2', {
url: "/route2",
templateUrl: "..."
})
.state('route3', {
url: "/route3",
templateUrl: "..."
});
This works and for .../checkout/1#/, .../checkout/1#/route2, .../checkout/1#/route3.
However, it also work in my other SPA views which I do not want. So, if I do another rails view that uses another SPA, e.g. .../item/1 then the above route will also work for .../item/1#/ and .../item/1#/route2, etc.
Instead, I would like each to be it's own SPA and not conflict with each other. I am not sure how to do this. Can ui-router be somehow namespaced using the base url or can I have independent SPAs that have different stateProviders? Any thoughts on how I should go about this?
Thanks
Each SPA should have its own angular module defining an application with its own state definitions. So there can't be any conflict.

Backbone and Laravel: Prevent access to Laravel controller method

First of all, sorry for my bad english language skills.
I am using Laravel and Backbone.js for small web app. In my backbone collection I'am defining urlRoot: 'test/cont1'. How can I "allow" backbone to asynchronously go to that URL but prevent user to manually go to the same URL by typing it in web browser (User will then get some json response that i don't want for him to see).
Don't know if this is what you want but you could add a filter and simply do if ( ! Request::ajax()) App::abort();
EDIT: a better example...
Route::filter('api', function($route, $request)
{
if ( ! $request->ajax()) App::abort(404);
});
Then in your controllers add the api filter.

Backbone.js with Rails

I'm currently trying Backbone.js along with a rails app. My problem is, that I don't know how to implement the Backbone controllers and views with my rails app. I've read a lot of tutorials, but they are always using just one controller in backbone.js.
For example, I have two controllers in rails.
Activities Controller
Includes two views, a google map and a search field. The google map is inserted with a backbone view, the searchfield is in HTML and gets its functionality through a backbone view.
The search field should fetch data from my rails model and display markers inside the map.
And the other one is
Users Controller
Here the users profile is viewed, and I want to add some ajax functionality like updating values and other things
In my application.js I start the app using
var App = {
Views: {},
Controllers: {},
Collections: {},
init: function() {
new App.Controllers.Activities();
new App.Controllers.Users();
Backbone.history.start();
}
};
$(function() {
App.init();
});
The problem is, that I don't need the Activities controller in my User Profile and the Users controller in the Rails Activities controller. How could I solve this? Should I try reading the current URL within javascript and then decide which controller is used?
Or should I put the JavaScript file into the application.html.erb and then decide here which controller should be used?
Or is this the wrong way to use backbone.js controllers?
Am I getting sth wrong with the structure of backbone.js? Or am I using the Controllers in a wrong way?
Another question is, how to add little JavaScript, in particular jQuery, functionality through Backbone.js? For example, I want to remove the label inside a field, when the user clicks into the field. Or I want to do some tab-functionality and just toggle the visibility of some elements.
Should I create for each element that is using javascript a Backbone view? Or is this overload?
Hope I made myself clear and anybody can help,
thx!
Why not make use of the routes feature Backbone provides to decide which method to call? The activities controller would contain only routes use for activities, the user controller only for the user handling, and so forth.
Like this you can instantiate the controller just as you do and the routing will decide what happens based on the current location's hash.
If you can't use links with hashes (or there are no such links on your page), I'd simply name my view containers specific enough to attach events only for the current view when needed.
jQuery plugins etc. belong into views IMO. Same goes for your tabs and input hint toggle.
Update
On a general level (and I would not necessarily recommend doing it this way): If you have two methods:
// should be only called for the 'Foo' controller
function foo() {
alert("FOO");
};
// should be only called for the 'Bar' controller
function bar() {
alert("BAR");
};
and want to call only one of them depending on the current Rails controller, create a small helper:
e.g. in you *helpers/application_helper.rb*
def body_class
controller.controller_name
end
then call this method in your layout file (or header partial):
<body class="<%= body_class %>">
…
and use e.g. jQuery to "split" your JS execution:
if ($('body').hasClass('foo')) {
foo();
} else if ($('body').hasClass('bar')) {
bar();
}
I personally use jammit (from the same author of backbone). You can group stylesheets and javascripts files by module and use them on your different pages. So you create a module for your activities view and another for your user view each requiring the necessary JavaScript file. Two nice things about this:
you have only code used on the page loaded on the page
jammit comprsses everything for you
This is the way to go when not creating a single page web app where you relies on # routes to navigate from one controller to another. In your case you have multiple single page apps inside a main rails app.
Im a Backbone.js newb, so please someone correct me if Im wrong, but I think youre confusing what Backbone controllers are used for.
Backbone.js controllers basically consists of hashbang routes(similar to Rails routes) and actions that these routes call. For instance if you have a rails route that will render a view at http://mysite.com/backbone_test and you have a following backbone route:
var MyController = Backbone.Controller.extend({
routes: {
"foo/:bar": "myFirstFunction"
},
myFirstFunction: function(bar){
console.log(bar);
});
then if you go to http://mysite.com/backbone_test#foo/THIS-IS-AMAZING then MyController.MyFirstFunction gets executed and "THIS-IS-AMAZING" gets logged in JS console.
Unless you have a direct need for this sort of hashbang-related functionality, such as saving a state of your JavaScript application via an url (for example: http://my.app.com/#key=value&key=value&ad-infinitum=true ) Id advise against using Backbone controllers. You can get all of the functionality u described via Models Collections and Views.
Nice thing about Controllers and Backbone in general is that its modular and different parts can be used independently.
I guess the summary of this answer is that if you dont have a single page javascript application, do not use Backbone Controllers, rely on your rails controllers instead.

Resources