Retrieving form control values in AngularJS without using data binding

I recently implemented a form using rails scaffolding, which is functioning properly. However, I am now looking to enhance it by adding a new Angular controller. The purpose of this controller would be to calculate a score/progress bar that displays the percentage completion of the user's application.

One issue I encountered during the update process is that Rails assigns a value to the form control, but ngModel resets that controller because I did not initialize the values in the JavaScript section.

In the code snippet below, you can see that during editing, the side_id control becomes empty:

Is there a way to efficiently read the form's various controls without having to resort to data binding?

<ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
    <li class="active"><a href="#general" data-toggle="tab">General Data</a></li>
    <li><a href="#location" data-toggle="tab">Location</a></li>
    <li><a href="#suppl" data-toggle="tab">Additional Data</a></li>
    <li><a href="#photos" data-toggle="tab">Photos</a></li>
  </ul>

  <div id="my-tab-content" class="tab-content">
    <div class="tab-pane mypanel active" id="general">
      <br/>
      <div class="form-group">
        <div class="col-md-2">
          <div class="field">
            <%= f.label :side_id %><br>
            <%= f.collection_select(:side_id, Side.all,:id,:label,{}, {:class => "form-control", "ng-model" => "side_id"}) %>
            {{side_id}}
          </div>          
        </div>
        <div class="col-md-4">
          <div class="field">

Answer №1

One way to set the initial value of ngModel in AngularJS is by creating a directive that takes the default value from HTML.

Check out a live example on jsfiddle.

angular.module('ExampleApp', [])
  .controller('ExampleController', function($scope) {
    $scope.options = [{
      id: 0,
      name: "No"
    }, {
      id: 1,
      name: "Yes"
    }, {
      id: 2,
      name: "Unknow"
    }];
  })
  .directive('initValue', function() {
    return {
      restrict: "A",
      require: "ngModel",
      scope: {
        initValue: "=",
        ngModel: "="
      },
      link: function(scope) {
        scope.ngModel = scope.initValue;
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <input ng-model="id" init-value="'dfdffd'">
    <pre>id={{id}}</pre>
    <select ng-model="idSelect" init-value="'2'">
      <option value="0">No</option>
      <option value="1">Yes</option>
      <option value="2">Unknow</option>
    </select>
    <pre>idSelect={{idSelect}}</pre>
    <select ng-model="idSelect2" init-value="1" ng-options="item.id as item.name for item in options">
    </select>
    <pre>idSelect2={{idSelect2}}</pre>
  </div>
</div>

Answer №2

const selectedSideID = angular.element('#classified_side_id').val();

Furthermore, I am monitoring the element value change through event handlers.

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

Looking to create a pop-up using javascript, css, or jQuery?

When visiting digg.com and clicking the login button, a sleek in-screen popup appears to input user data. I'm curious about the best way to achieve this on my own site. It is built with RoR and includes some Javascript elements. Searching for "javasc ...

Rotating Images with jQuery using the 'jQueryRotate' extension

Trying to create a hover effect where one div triggers the rotation of an image in another div. Experimenting with the jQueryRotate plugin found at http://code.google.com/p/jqueryrotate/ Check out my code on jsFiddle. The green square is rotating with CS ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

How to make a div in Javascript smoothly slide out when it appears

Looking to add some smooth sliding animation to this basic JS code instead of the glitchy appearance it currently has. I've experimented with different options but haven't had any success, any suggestions? Here's the code snippet along with ...

Retrieving multiple selected row values using an ASP Repeater

Within my repeater, I have three values bound: a visible "User Name" column, a visible "Business" column, and a hidden field called "UserId". My goal is to implement the following functionality: when a row is clicked, it should highlight in a different c ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

When the React application loads, loadingbar.js will be mounted initially. However, as the props or states are updated, the object

I recently made the switch from using progressbar.js to loadingBar.js in my React application for widget progress. Everything was working smoothly with progressbar.js, but once I switched to loadingBar.js, I encountered a strange issue. After the page load ...

Positioning a fixed div within a responsive div using AngularJS and Bootstrap

I'm currently working on a page layout that consists of a fixed sidebar on the left side and a main container taking up the rest of the page on the right. Inside this right-side container, which is a div, there are 2 elements. <div class="col-sm-1 ...

Identify the ANGLE using JavaScript

I'm experiencing an issue with my WebGL / Three.js game where there is an unhelpful shader program linking error when ANGLE is used for providing WebGL. To address this, I am looking to implement a prominent warning specifically for ANGLE users on the ...

Is it necessary to compile the React JavaScript project before uploading it to npm?

Hey there, I'm currently in the process of publishing a React JavaScript component on npm. I have a question regarding whether or not I need to build the project and deploy the build folder. Your input would be greatly appreciated. Thanks! ...

Obtaining and transferring identifiers for jQuery code execution

My goal is to create a script that dynamically changes the content of a webpage using a foreach array. The HTML structure I am working with looks like this: <div id="bigleftproject"> <p>content to be replaced</p> </div> <div ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

Using ng-if with the selected tag within a select option

I am currently working on building an Angular JS application and I need to create a select option similar to the one shown below. <select class="form-control" ng-model="rc.status" ng-init="rc.status=1"> <option value="1" selected="selected"&g ...

The date entered in an HTML input is being interpreted as "incorrect" by the system

Upon inputting 3/15/2019 as the date and then checking the time with console.log(fromDate), the output appears as Thu Mar 14 2019 19:00:00 GMT-0500 (Central Daylight Time). Why is it not showing Fri Mar 15 2019 00:00:00? Could this be related to the tim ...

Utilize jQuery to dynamically apply Bootstrap classes while scrolling through a webpage

Having an issue with jQuery. Trying to include the fixed-top class (Bootstrap 4) when scrolling, but it's not working as expected. jQuery(document).ready(function($){ var scroll = $(window).scrollTop(); if (scroll >= 500) { $(".robig").a ...

building a JSON object from scratch

After searching for multiple solutions to my problem, I have not been able to find a working code that fits the data I have. I am looking to transform this dataset into multiple objects: [{"creature":{"id":1,"name":"R.I.P.","sprite_location":null,"health ...

Set the array back to its initial value of 1 using jQuery and

After making substantial edits to this question, I find myself in need of a reset button for the code. The current item needs to be reset back to 1 so that I can use it again, but the issue lies in the fact that only the current item is reset while the hig ...

AngularJS: Embedding a webpage within a <div> container

I recently came across this question in STO, but unfortunately, I couldn't find a suitable answer. Currently, I am working with Angular 1.0 and sending an AJAX request to the server to retrieve a list of URLs in the following format: My challenge no ...

Incorporate real-time validation observables with the power of rxjs

Currently, I am working on implementing an observable for a validation task. There are 2 observables, frontEndValidate and backEndValidate, which I need to process sequentially in a specific order. If any of these observables throws an error, the entire pi ...