Inconsistencies observed in the behavior of Rails JavaScript assets with respect to

Currently delving into the world of Rails while also incorporating Angular into my project.

Let's build a basic application from scratch.

1). Start off by creating a new Rails app:

rails new hello_rails

2). Include the angular gem in your Gemfile

gem 'angularjs-rails'

3). Install the bundle

bundle install

4). Add angular to the JavaScript manifest located in

app/assets/javascripts/application.js

//=require angular

5). Generate the welcome index

rails generate controller welcome index

6). Fill index.html.erb with a simple Angular "hello world" example

 <div style = "background-color: grey">
    this is index.html.erb<br>

  <div ng-app="">
    <p>Name : <input type="text" ng-model="name"></p>
    <h1>Hello {{name}}</h1>
</div>

</div>

7). Make modifications to application.html.erb as well

<pre>
<!DOCTYPE html>
<html>
<head>
  <title>HelloRails</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body style = "background-color:green">

  This is application.html.erb <br>

   <%= link_to "click here to go home", root_path %> <br>

A yeild statement is below: <br>
<%= yield %>

</body>
</html>

8). Set the root route to welcome#index in config/routes.rb

root 'welcome#index'

Once you have completed these steps, run the application - it should work without any issues.

Upon completion, you should see something like this:

https://i.sstatic.net/OMJBS.png

The Angular integration should be functional as shown:

https://i.sstatic.net/Djlh3.png

However, if you click on the link to return to root_path, the functionality may cease.

https://i.sstatic.net/1Wi0D.png

Moreover, adding some Angular code to the application.html.erb might disrupt the existing Angular functionality.

<div ng-app="">
<p>Name : <input type="text" ng-model="home_name"></p>
<h1>Hello {{home_name}} at home</h1>
</div>

https://i.sstatic.net/9y2QT.png

Can you explain why Rails behaves in this manner?

Answer №1

After following your instructions and setting up Angular in the same manner as you did, I encountered a similar issue. Removing turbolinks resolved the initial problem I was facing. The second issue stemmed from incorrect usage of the ngApp directive.

Reading through AngularJS ngApp Documentation:

The ngApp directive serves as the root element of the application and is typically positioned near the page's root element.

In addition,

Only one AngularJS application can be automatically bootstrapped per HTML document.

Upon inspection, it appeared that you had ng-app="" twice within your code. As only one application can be bootstrapped, the first div housing angular code in your application.html.erb would function, while the other in index.html.erb would not.

To resolve this issue, consider placing ng-app="" on either your <body> or <html> tags in your application.html.erb based on your requirements. If you intend for Angular to manipulate elements within the <head> section (such as the page title using <title>), then position ng-app="" on your <html> tag. Otherwise, place it on your body tag.

<pre>
<!DOCTYPE html>
<html>
<head>
  <title>HelloRails</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
<body style = "background-color:green" ng-app="">

  This is application.html.erb <br>
  <div>
    <p>Name : <input type="text" ng-model="home_name"></p>
    <h1>Hello {{home_name}} at home</h1>
  </div>

   <%= link_to "click here to go home", root_path %> <br>


A yeild statement is below: <br>
<%= yield %>

</body>
</html>

Effectively Manipulating Page Title with ngApp in <html>

<html  ng-app="">
<head>
  <title>{{home_name}} | HelloRails</title>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
</head>
...

These adjustments worked perfectly!

https://i.sstatic.net/qrRZt.png

For further guidance on integrating Angular with Rails and correctly configuring turbolinks with Angular, check out these resources: Resource 1
Resource 2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Error encountered while trying to display a Jbuilder JSON object in JSON format

Currently, I am in the process of developing a student tracking website using RoR. Within my model, I have written the following code to construct json: self.as_json json = Jbuilder.new do |j| j.courses student_courses do |course| j.(course, : ...

Understanding how to open a PNG file in the client-side browser and transform it using PNGJS in React

Utilizing React JS for my application development is a current focus of mine. I have a solid understanding of how to import images within the client/browser folder structure. For example: import maze_text from '../../mazes/images/maze_text.png&apos ...

Utilize Angular functions in every controller in your application

Currently, I have important functionality code within app.run(function... in Angular: app.run(function($rootScope, $window) { // Obtain window dimensions $window.width = angular.element($window).width(); $window.height = angular.element($window).he ...

Understanding Conditional Statements in JavaScript

Excuse my lack of experience, but I have a query. I usually learn by studying examples, but this specific part of the Javascript code is proving to be quite challenging for me. if (lvl == "level0" || lvl == "level2" || lvl == "level3") { ...

Tips for successfully passing an object with a list property in an ajax request

I have encountered a similar problem to This previous question, but I am struggling to implement the solutions provided. I am unsure of where to include the ModelBinder code mentioned in the responses, so I will explain my issue here. I am working with a s ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

The JavaScript jump function quickly moves back to the top of the webpage

Issue Resolved To prevent the view from jumping to the top of the page, I have implemented three options: Set the href attribute to href="#!" Set the href attribute to href="javascript:;" Pass the object to the event-handler and preve ...

Tips on how to properly display the date in v-Calendar

I'm struggling to format the date output from the v-calendar. Currently, it appears like: Fri Jul 31 2020 00:00:00 GMT+0200 (utc summertime) However, I would like it to display as 2020-07-28. I have searched through the documentation but couldn' ...

Arrange each segment of the smaller array into its own respective row

I have a large array that I have converted into a multidimensional array consisting of 7 smaller chunks or groups. I now want each of these groups to be displayed in a separate row of a table, with a number of `td` elements equal to the number of items in ...

ngPattern problem

As I work on creating a more user-friendly expiration date input for a credit card checkout form, I encountered a challenge. The goal is to automatically insert a " / " between the expiration month and year as the user types. However, the issue arises when ...

Retrieve data from the endpoint using Routing.generate to access the JSON route

My goal is to retrieve data from the database within a Symfony controller, encode the response into JSON format. The code snippet for this functionality is shown below: /** * @Route("/jsondata", options={"expose"=true}, name="my_route_to_json_data") */ ...

Focused Filtering in DataGrid Pagination

Seeking to adjust the font size of numerical values (10, 25, and 50 as shown in the screenshot below) within rows per page selection within a pagination section of a DataGrid component. https://i.sstatic.net/PnIDa.png After inspecting each number, it was ...

Techniques for eliminating text enclosed by double parentheses in javascript

I am currently working on extracting data from Wikipedia, but I am facing a challenge with removing content enclosed in multiple parentheses. While I can successfully remove single parentheses using content.replace(/\s*\(.*?\)\s*/g, &ap ...

The "checked" property is absent in the ASP.NET checkbox within the gridview

In my asp.net gridview control, the checked property seems to be missing. I am trying to access the checked property using jquery Gridview structure: <Columns> <asp:TemplateField> <ItemTemplate> ...

React:error:unexpected punctuation

I encountered an issue with this code within the render() function, specifically on the line where I am returning a value and it shows an unexpected token error. Here's the snippet of the code. class PuzzleGame extends React.Component { construct ...

Using Single Quotes as Parameters in JavaScript

I'm currently facing an issue with a function that is designed to populate a field in the parent window when clicked. Specifically, it is meant to fill in a text field with a name. The challenge I am encountering arises when the field contains a sing ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Is there an Angular Profile service offering getter and setter properties?

Can a singleton Angular service be created with getters and setters along with logic implementation? I was provided with the following code snippet and tasked with replicating it in an Angular service. Although it may seem straightforward, I'm finding ...