Hi I followed a tutorial: http://omarriott.com/aux/angularjs-html5-routing-rails/
Here's my manual.js.coffee.erb
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
#= require_tree ./templates
#Bento = angular.module('bento', ['ngRoute', 'ngResource', 'ngSanitize', 'ui.bootstrap', 'infinite-scroll'])
# Pre-cache templates
Bento.run ($window, $templateCache) ->
templates = $window.JST
for fileName of templates
fileContent = templates[fileName]
$templateCache.put(fileName, fileContent)
# Note that we're passing the function fileContent,
# and not the object returned by its invocation.
#= require_tree ./controllers
#= require_tree ./services
#= require_tree ./directives
My routes.js.coffee.erb
#Bento.config ["$routeProvider", ($routeProvider) ->
$routeProvider.when("/",
controller: "ActivitiesController"
templateUrl: "<%= asset_path('templates/user/activities.html.haml') %>"
redirectTo: (current, path, search) ->
if search.goto
"/" + search.goto
else
"/"
).when("/projects/activities",
controller: "ProjectAllActivitiesController"
templateUrl: "<%= asset_path('templates/projects/activities.html') %>"
redirectTo: "/example"
).when("/projects/:id",
controller: "ProjectCtrl"
templateUrl: "<%= asset_path('templates/projects/list.html') %>"
redirectTo: (current, path, search) ->
if search.goto
"/projects/:id" + search.goto
else
"/projects/:id"
).otherwise redirectTo: "/"
]
And lines that I added to my config/routes.rb file
match "api" => proc { [404, {}, ['Invalid API endpoint']] }, via: [:post]
match "api/*path" => proc { [404, {}, ['Invalid API endpoint']] }, via: [:post]
match "/*path" => redirect("/?goto=%{path}"), via: [:post]
Since I'm using rails 4, I need to add a via
# sign is adding whenever I refresh my root path localhost:3000/ but it's not working in nested URLs like localhost:3000/projects/1 it's still reading my routes for RAILS.
PS: Whenever i refresh localhost:3000/projects/activities for example, it's still reading my rails routes instead of going to localhost:3000/example.
Related
I'm following along with the Angular/Rails tutorial at Thinkster and I've run into an issue which seems to be most likely be Angular-related. Everything works just fine until I get to the Angular Routing section. Simply put, the inline templates within the <script> tags do not load in the <ui-view></ui-view> element. I originally thought this may be due to having opened the page locally as a file rather than having it loaded from a server, but the same problem persists even after integrating Rails (using an older version of Sprockets, as pointed out in this similar but unrelated issue).
When I load the index page in either the browser as a file or as a URL when running the Rails server, I've inspected the HTML and, sure enough, the only thing it shows in the code are the divs and an empty <ui-view> element, indicating something just isn't adding up correctly. I've tried various things, including:
Using the newest version of ui-router (0.2.15 at this writing) rather than the version in the tutorial
Using <div ui-view></div> instead of <ui-view></ui-view>
Changing the value of 'url' in the home state to 'index.html', including using the full path to the file (file:///...)
Putting the contents of the inline <script> templates into their own files (without the <script> tags, of course) and specifying the 'templateUrl' field using both relative and full paths
Trying both Chrome and Firefox just to be extra certain
None of these things have worked, even when accessing http://localhost:3000/#/home when the Rails server is running after having integrated Angular into the asset pipeline in the Integrating the Front-end with the Asset Pipeline section of the tutorial. Indeed, the route loads but does not show anything more than a completely blank page with a lonesome and empty <ui-view> element when inspecting the HTML using Chrome's dev tools.
Given that the issue seems to occur even before the Rails portion, it does seem like something to do with Angular itself, but I've got no clue what's going on, especially since I've followed along to the letter.
I'm using Bower to manage the Angular dependencies and the HTML does show that the Angular javascript files in both the app/assets/javascripts directory and in the vendor/assets/bower_components directory are being loaded properly in the <head> section, so everything seems to be okay on the asset pipeline integration.
Versios I'm using:
Rails: 4.2.3
Ruby: 2.2.1p85
Angular: 1.4.3
ui-router: 0.2.15
The code I've got for the major moving parts is below:
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
<body ng-app="testApp">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
</body>
</html>
app/assets/javascripts/app.js
angular.module('testApp', ['ui.router', 'templates']).config(['$stateProvider', '$urlRouteProvider', function($stateProvider, $urlRouteProvider) {
$stateProvider
.state('home', {
'url': '/home',
'templateUrl': 'home/_home.html',
'controller': 'MainCtrl'
})
.state('posts', {
'url': '/posts/{id}',
'templateUrl': 'posts/_posts.html',
'controller': 'PostsCtrl'
});
$urlRouteProvider.otherwise('home');
}]);
app/assets/javascripts/application.js
//= require angular
//= require angular-rails-templates
//= require angular-ui-router
//= require_tree .
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
respond_to :json
def angular
render 'layouts/application'
end
end
config/routes.rb
Rails.application.routes.draw do
root to: 'application#angular'
end
app/assets/javascripts/home/mainCtrl.js
angular.module('testApp').controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
$scope.posts = posts.posts;
$scope.addPost = function() {
if (!$scope.title || $scope.title === "")
return;
$scope.posts.push({
'title': $scope.title,
'link': $scope.link,
'upvotes': 0,
'comments': [
{'author': 'Some Person', 'body': 'This is a comment.', 'upvotes': 0},
{'author': 'Another Person', 'body': 'This is also a comment.', 'upvotes': 0}
]
});
$scope.title = "";
$scope.link = "";
};
$scope.incrementUpvotes = function(post) {
post.upvotes++;
};
}]);
app/assets/javascripts/posts/postsCtrl.js
angular.module('testApp').controller('PostsCtrl', ['$scope', '$stateParams', 'posts', function($scope, $stateParams, posts) {
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function() {
if($scope.body === '')
return;
$scope.post.comments.push({
'body': $scope.body,
'author': 'user',
'upvotes': 0
});
$scope.body = '';
};
}]);
app/assets/javascripts/posts/posts.js
angular.module('testApp').factory('posts', ['$http', function($http) {
var o = {
'posts': []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data) {
angular.copy(data, o.posts);
});
};
return o;
}]);
If any other code is required to help uncover the problem, please let me know and I'll supply anything requested.
it seems that the angular-ui-router is incompatible with the new Rails sprockets. To fix this, add this earlier version of sprockets to your gemfile:
gem 'sprockets', '2.12.3'
And then run bundle update sprockets.
This was answered a few times in other similar questions, like the one below:
Angular Rails Templates just not working
$urlRouteProvider in my code should've been $urlRouterProvider. Be sure to double-check everything, folks, and make good use of the console!
I have followed all the github issues on HTML5Mode breaking Angular apps in 1.5. I am having the same problem but none of the fixes are working for me.
Im doing the following:
<base href="/">
and
get '/*path', :to => "menus#index"
and
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/edit", { templateUrl: "/assets/menus/edit.html", controller: "MenuSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items", { templateUrl: "/assets/menus/items.html", controller: "MenuItemCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections", { templateUrl: "/assets/menus/option_sections.html", controller: "MenuOptionSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections/:op_sec_id/options", { templateUrl: "/assets/menus/options.html", controller: "MenuOptionCtrl" })
});
I am lost as to what to do next. I have tried every combination of routes and base[href].
Anybody have any ideas?
Also, I have followed this tutorial too. http://omarriott.com/aux/angularjs-html5-routing-rails/
Try this link
http://start.jcolemorrison.com/angularjs-rails-4-1-and-ui-router-tutorial/
If you have mount only single angularjs application then it is very straight forward. You need to make this entry in routes.rb
get '*path' => 'application#index'
And in your application.controller change the index method as below
def index
render layout: 'application'
end
The following link helped me to use rack-rewrite get which seems to work for me. Here is the link. Only the following code in config.ru would allow /api routes to rails:
# config.ru
# This file is used by Rack-based servers to start the application.
use Rack::Rewrite do
rewrite %r{^(?!.*(api|\.)).*$}, '/index.html'
end
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
I managed to get mine working with:
get '*path', to: redirect('/#/%{path}')
The template I bought was working without hash after the first load but if you refresh the page it does not work. I tried manually adding the hash like /#/page and the above routing does it automatically.
I have a working copy of an Angular app backed by a Rails app.
I put the Angular templates inside app/assets/templates/devices/ and when I need to use a template, I do it like this:
when("/devices", {templateUrl: "assets/devices/select.html", controller: "DevicesListCtrl"})
This works fine in my local machine, but when uploading to Heroku, I get the following error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Any thoughts on how should I approach this?
I have also tried using the following:
//= depend_on_asset devices/index.html
//= depend_on_asset devices/show.html
//= depend_on_asset devices/select.html
window.App = angular.module('TestApp', ['ngResource', 'ngRoute']);
App.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/devices", {templateUrl: "<%= asset_path('assets/devices/index.html') %>", controller: "DevicesListCtrl"}).
when("/devices/:id", {templateUrl: "<%= asset_path('assets/devices/show.html') %>", controller: "DevicesShowCtrl"}).
when("/", {templateUrl: "<%= asset_path('assets/devices/select.html') %>", controller: "DevicesSelectCtrl"}).
otherwise({redirectTo: '/devices'});
}]);
But I still get a 404...
I believe that you shouldn't add 'assets' in the URL.
Just do this:
asset_path('devices/index.html');
i am attempting to use emberjs to render some pages within my so that the content isnt reloaded
the issue i am having is that nothing seems to be rendering
application.js
#= require jquery
#= require jquery_ujs
#= require jquery.ui.all
#= require date
#= require misc
#= require foundation
#= require handlebars
#= require ember
#= require ember-data
#= require_self
App = Ember.Application.create(
LOG_TRANSITIONS: true
ready: ->
console.log "App ready"
return
)
App.Router.map ->
#resource "admin/pages",
path: "/admin/pages"
return
App.IndexRoute = Ember.Route.extend(redirect: ->
#transitionTo "admin/pages"
return
)
App.NewslinksRoute = Ember.Route.extend(model: ->
App.Page.find()
)
DS.RESTAdapter.reopen namespace: "admin/pages"
App.Store = DS.Store.extend(revision: 13)
App.Page = DS.Model.extend(name: DS.attr("string"))
# for more details see: http://emberjs.com/guides/application/
#window.Grokphoto = Ember.Application.create()
$ ->
$(document).foundation()
return
routes.rb
match 'admin' => 'admin/pages#index'
namespace :admin do
resources :events, :only => :index
resource :photographer, :only => [:edit, :update]
resources :pages
resources :posts
resources :galleries
resources :private_galleries do
get :invite, :on => :member
put :send_invite, :on => :member
end
resources :photos, :only => [:edit, :update, :destroy] do
put 'sort', :on => :collection
end
end
then in /assets/javascripts/templates/admin/page/index.hbs i have the following
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Ember - Latest" />
<meta charset=utf-8 />
<title>Ember</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://builds.emberjs.com/ember-latest.js"></script>
<script src="http://builds.emberjs.com/ember-data-latest.js"></script>
</head>
<body>
<script type="text/x-handlebars">
<h2>Ember Works</h2>
</script>
</body>
</html>
if i can just get this to render out i should be able to work the rest out
Emberjs and Rails in 2 minutes
rails new app
cd app
# remove gem 'coffee-rails' from Gemfile if not needed
echo "gem 'ember-rails'" >> Gemfile
echo "gem 'ember-source', '1.3.0'" >> Gemfile
bundle
rails g ember:bootstrap
rails g controller home index
(Remove the lines in the view file)
# config/routes.rb
root 'home#index'
# config/environments/development.rb
echo "Hello world" >> app/assets/javascripts/templates/index.hbs
http://localhost:3000 Voila :)
Rails normal flow
Here is how emberjs in Rails works. emberjs is just a javascript that can even do routing(changing urls like /#/posts ) .
In Rails, when a request is made to /admin which maps to 'admin/pages#index' in your case will do these.
go to the particular controller action.
render the layout file views/layouts/application.html.erb
then yield your admin/pages#index view inside of it.
With Emberjs
The same thing happens when you have emberjs too, nothing special, nothing changes this order, except that you don't need anything to be render from your admin/pages#index view file, it can be blank.
But you need layouts/application.html.erb as you have all your javascript under it as
<%= javascript_include_tag "application" %>
Now the flow for /admin
goes to controller action.
renders layout file which also has javascript that also involve emberjs, along with handlebars which is again js related.
yields your view file, which can be blank. As emberjs will insert the compiled handlebar template for us.
For emberjs to work in Rails.
Your layout file needs to load javascript with your application.js.
Then create a file app/assets/javascripts/templates/index.hbs
Hello world
It should work! I suggest you try out creating new rails project to get some idea and tehn start migrating.
I used the gem to install ckeditor. As such there is no config.js in the project (there is in the actual gem folder that I don't want to modify). The install did create a ckeditor.js in the config/initializers folder that would seem to be the correct place to put the tool bar definition. But everything I have tried to get that to work throws a variety of syntax or method not found errors. Has anyone had success with this? If so a quick example would be very helpful.
My current ckeditor.js is:
# Use this hook to configure ckeditor
if Object.const_defined?("Ckeditor")
Ckeditor.setup do |config|
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default), :mongo_mapper and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require "ckeditor/orm/active_record"
# Allowed image file types for upload.
# Set to nil or [] (empty array) for all file types
# config.image_file_types = ["jpg", "jpeg", "png", "gif", "tiff"]
# Allowed attachment file types for upload.
# Set to nil or [] (empty array) for all file types
# config.attachment_file_types = ["doc", "docx", "xls", "odt", "ods", "pdf", "rar", "zip", "tar", "swf"]
end
end
1.Add following in application.js
//= require ckeditor/ckeditor
//= require_tree ./ckeditor
2.Add a config.js in app/assets/javascript/ckeditor
Sample config.js
if(typeof(CKEDITOR) != 'undefined')
{
CKEDITOR.editorConfig = function(config) {
config.uiColor = "#AADC6E";
config.toolbar = [
[ 'Bold', 'Italic', 'Underline', 'Strike' ],
[ 'NumberedList', 'BulletedList', 'HorizontalRule' ],
[ 'Blockquote' ],
[ 'Undo', 'Redo' ],
[ 'insertResolved' ],
[ 'Source' ]
];
}
} else{
console.log("ckeditor not loaded")
}
I have the same problem as yours. At first, I followed Config rails with asset pipeline but it doesn't work for me. Then I realized that the author of that link only create a new style of toolbar. You need to call it in the view also. That means you need to add this line
input_html => {:toolbar => 'MyToolbar'}
to make it works.
In order to test if the config.js is working, you can check the source of your webpage to see whether assets/javascripts/ckeditor/config.js is added.
Another way to check is to edit the editor color by uncommenting this line: config.uiColor = '#AADC6E'. If the color of the editor changes then it works.
I also made a stupid mistake that I include the ckeditor js files two times: once in the application.js, once in the layouts/application.html.haml file. Don't know whether this is the source of the problem or not. You can try.
Hope this helps.
this worked for me:
How to configure CKEditor in Rails 3.1 (gem + Asset Pipeline)
just save the snippet given in the answer, in config.js file
May be my comment on github will help you https://github.com/galetahub/ckeditor/issues/136#issuecomment-8870692
This is the updated answer to Rails 4.1 with ckeditor 4.1.0 to custom configure the ckeditor toolbar.
In your view, using simple_form, you need to config the input like this example:
_FORM.HTML.ERB
<%= simple_form_for(#foo) do |f| %>
<%= f.input :bar, as: :ckeditor %>
<%= f.button :submit %>
<% end %>
In your Javascript assets you need to create a folder called "ckeditor" and in there create a file called "config.js"
../JAVASCRIPTS/CKEDITOR/CONFIG.JS
CKEDITOR.editorConfig = function(config) {
//config.language = 'es'; //this could be any language
config.width = '725';
config.height = '600';
// Filebrowser routes
// The location of an external file browser, that should be launched when "Browse Server" button is pressed.
config.filebrowserBrowseUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Flash dialog.
config.filebrowserFlashBrowseUrl = "/ckeditor/attachment_files";
// The location of a script that handles file uploads in the Flash dialog.
config.filebrowserFlashUploadUrl = "/ckeditor/attachment_files";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Link tab of Image dialog.
config.filebrowserImageBrowseLinkUrl = "/ckeditor/pictures";
// The location of an external file browser, that should be launched when "Browse Server" button is pressed in the Image dialog.
config.filebrowserImageBrowseUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads in the Image dialog.
config.filebrowserImageUploadUrl = "/ckeditor/pictures";
// The location of a script that handles file uploads.
config.filebrowserUploadUrl = "/ckeditor/attachment_files";
// You could delete or reorder any of this elements as you wish
config.toolbar_Menu = [
{ name: 'document', items: ['Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates'] },
{ name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
{ name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt'] },
{ name: 'tools', items: ['Maximize', 'ShowBlocks', '-', 'About'] }, '/',
{ name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat'] },
{ name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl'] },
{ name: 'links', items: ['Link', 'Unlink', 'Anchor'] }, '/',
{ name: 'styles', items: ['Styles', 'Format', 'Font', 'FontSize'] },
{ name: 'colors', items: ['TextColor', 'BGColor'] },
{ name: 'insert', items: ['Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak'] }
];
config.toolbar = 'Menu';
return true;
};
The config for the application.js is like this, notice that the order of ckeditor and require_tree is important
APPLICATION.JS
//= require jquery
//= require jquery_ujs
//= require ckeditor/init
//= require_tree .
Now in your ckeditor.rb you should uncomment this line "config.asset_path" and add the path to the config.js file that you created before wich is "/assets/ckeditor/"
../CONFIG/INITIALIZERS/CKEDITOR.RB
# Use this hook to configure ckeditor
Ckeditor.setup do |config|
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default), :mongo_mapper and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require "ckeditor/orm/active_record"
# Customize ckeditor assets path
# By default: nil
config.asset_path = "/assets/ckeditor/"
end
I hope it helps :D!