AngularJS restricts inputs to be read-only

I'm facing an issue with readonly inputs in AngularJS. I have a select element that changes the values of readonly inputs through a script. However, when I attempt to display these values using ng-model in a table as {{ng-model}}, they don't appear.

<select name="well" onChange="Update(this.value)" ng-model="well" required>
<option value="Well-01">Well-01</option>
<option value="Well-02">Well-02</option>
<option value="Well-03">Well-03</option>
</select>
<label>Region:</label>
<input type="text" name="region" value="South" ng-model="region" disabled>
<label>State:</label>
<input type="text" name="state" value="Oklahoma" ng-model="state"  disabled>
<label>Field Office:</label>
<input type="text" name="office" value="Ringwood" ng-model="office" disabled>

Fiddle: http://jsfiddle.net/NKyps/7/

It displays {{well}} when I change it, but the inputs are not shown. Thanks for your assistance. PS: If anyone knows how to set a default option (e.g., Well-01) so that the inputs are filled when the document is loaded, please share.

Answer №1

It seems that the issue lies in the attributes not being properly bound to a model. When using {{variable}}, Angular expects them to be binding with a specific model.

I have included the scope model in your tags:

<form ng-controller="Sarapastrule" name="form">
</form>

Please review: http://jsfiddle.net/NKyps/9/

Answer №2

According to Bart, it seems you might be missing some fundamental AngularJS concepts and may benefit from reading the AngularJS tutorial available at http://docs.angularjs.org/tutorial.

In AngularJS, two-way data binding is essential. It handles updating the DOM while developers mainly focus on updating the model. Directly accessing value properties of input fields is not the recommended approach in AngularJS.

I have made modifications to your jsFiddle to work properly, but I do suggest going through the tutorial to grasp the underlying principles of AngularJS better.

You can view the updated version here: http://jsfiddle.net/BnqZS/1/

It's important to establish a controller first to manage the business logic. Within the controller, keep an eye on and update the model accordingly. Instead of:

if (choice == "Well-01") {
    region.value = 'South';
    state.value = 'Oklahoma';
    office.value = 'Ringwood';
}

You should set up a watch on the model connected to the option input field and use code like this:

$scope.$watch('well', function(choice) {
  if (choice == "Well-01") {
        $scope.region = 'South';
        $scope.state = 'Oklahoma';
        $scope.office = 'Ringwood';
    }

}

Answer №3

Your approach involves working outside of angular and performing custom DOM manipulation, which goes against the core principles of angular.js. I have provided an updated fiddle here for reference.

To resolve this issue, it is recommended to use a controller with a scope to define the values of your model.

function ExampleController($scope) {

    $scope.Update = function () {
        if ($scope.well == "Well-01") {
            $scope.region = 'South';
            $scope.state = 'Oklahoma';
            $scope.office = 'Ringwood';
        }

        if ($scope.well == "Well-02") {
            $scope.region = 'North';
            $scope.state = 'Montana';
            $scope.office = 'Sidney';
        }

        if ($scope.well == "Well-03") {
            $scope.region = 'North';
            $scope.state = 'North Dakota';
            $scope.office = 'Tioga';
        }
    }

    $scope.well = 'Well-01';
    $scope.Update();
}

The primary issue with your current design is the attempt to manage two separate models, one in JavaScript and another in the DOM. Angular.js is optimized for handling DOM manipulation on your behalf, simplifying the task of updating your model. Instead of manually updating the DOM, focus on creating a view that generates itself from a model, allowing modifications only to the JavaScript model ($scope variable).

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

Transferring data using AJAX between an AngularJS frontend and a Node.js backend

Just a heads up: The main question is at the bottom in case you find this post too lengthy ;) I'm currently working on developing my first angularjs app and I've hit a roadblock when it comes to fetching data via ajax from my nodejs (express) se ...

Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is m ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

jQuery appears to be unresponsive or inactive

I'm trying to implement a jQuery script that will slide in a header after scrolling on the page, but for some reason, it's not working. When I reach the 3rd line, my code editor displays a !read only alert, suggesting there may be a syntax issue? ...

forever js is interfering with the operation of a different application

I currently have two very similar Node JS projects that I manage by starting and stopping them using Forever JS. Both projects can run simultaneously on different ports but, when I input the following command: forever stop index.js In one project direc ...

Tips for altering the scrolling rate of a container

I am trying to adjust the scroll speed of specific divs among a group of 5 divs. I came across a solution that changes the scroll speed for the entire document: http://jsfiddle.net/36dp03ur/ However, what I really need is a scenario like this: <div i ...

Storing information in a session within a callback function using Node.js Express

Within the following code snippet, my goal is to retrieve user information from the database and store it in a session. However, I am encountering an issue where the data is not being properly saved into the session variable as expected. Could this be du ...

Angular replaces the expected service with the value `false` instead of injecting the desired service

I have a controller defined like this: angular.module('myApp') .controller 'DetailController', ($rootScope, $scope, $routeParams, apiService) -> onStart = () -> fetchData() getAdditionalData() # more functi ...

Is Immutable state considered a key functional aspect in the ReactJs framework?

One key aspect of an imperative program is the emphasis on state and its modifications. When it comes to ReactJs, there is a push for more functional programming styles, such as using purity and higher-order functions. I'm curious to explore whether ...

Transforming Unicode escape sequences into symbols and displaying them in a DOM element

Using the latest versions of Firefox and Chrome with jQuery 1.x edge. When an ajax request returns a single line of minified JSON text like this: { "fromSymbol": "\\u04b0", "toCurrency": "AUD", "toSymbol": "\\u0024", "convFact ...

Is it possible to create an observable with RXJS that emits only when the number of items currently emitted by the source observables matches?

I am dealing with two observables, obs1 and obs2, that continuously emit items without completing. I anticipate that both of them will emit the same number of items over time, but I cannot predict which one will emit first. I am in need of an observable th ...

When using Express.js for file uploading, it is important to first verify that a file has been sent, set a maximum file size limit, and ensure

After working with expressjs for a month, I've encountered some issues with file uploads. Despite researching on Google and various blogs, I haven't been able to find answers to the following three questions: What do I need to do or what setting ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

Utilizing Javascript to create interactive images in HTML

Is there a way for JavaScript to open the current image in a new WINDOW when an ONCLICK event occurs? <script> function imgWindow() { window.open("image") } </script> HTML <img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

What is the reason for utilizing letters as function name and parameters in JavaScript?

(function (a) { var r = a.fn.domManip, d = "_tmplitem", q = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, b = {}, f = {}, e, p = { key: 0, data: {} }, h = 0, c = ...

How to Embed a Javascript (jquery) Variable within a JSON Object

I have searched everywhere for a "simple answer" to this problem, but unfortunately, I cannot find a solution that aligns with my understanding of JSON and jQuery. Perhaps I am too much of a beginner in JSON to accurately formulate the right question (and ...

Content that is dynamically generated by a database

I have been working on creating a unique wall feature for my website, inspired by Facebook. My aim is to allow users to submit form data and have it validated before storing it in a database. Additionally, I want this stored data to be displayed in a desig ...

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...