AngularJS ng-model directive binds an input field with a specific value

I encounter a challenge where my inputs, containing values, do not display the value when I apply an ng-model to each input field. Below is the snippet of my code:

student-list.html

<!--edit form-->
<div class="col s12" ng-show="dataForm">
  <div class="row">
    <div class="input-field col l6 s12">
      <input id="first_name" value="{{student[0].fname}}" type="text" class="validate">
      <label class="active" for="first_name">First Name</label>
    </div>
    <div class="input-field col l6 s12">
      <input id="last_name" value="{{ student[0].lname }}" type="text" class="validate">
      <label class="active"  for="last_name">Last Name</label>
    </div>
  </div>
  <div class="row">
    <div class="input-field col l6 s12">
      <input id="email" value="{{ student[0].email }}" type="text" class="validate">
      <label class="active"  for="email">E-mail Address</label>
    </div>
    <div class="input-field col l6 s12">
      <input id="age" value="{{ student[0].age }}" type="text" class="validate">
      <label class="active"  for="age">Age</label>
    </div>
  </div>
  <button class="btn waves-effect waves-light" ng-click="updateStudent()">Submit
  <i class="material-icons right">send</i>
  </button>
  <button class="btn waves-effect waves-light pink accent-3" ng-click="cancelEditStudent()">Cancel</button>
</div>
<!-- form -->
<table class="highlight responsive-table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Email</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="s in students | filter:searchStudent" ng-show="studentsPanel">
      <td>{{ s.fname }} {{ s.lname }}</td>
      <td>{{ s.age }}</td>
      <td>{{ s.email }}</td>
      <td><a href="javascript:void(0)" ng-click="editStudent(s.id)">Edit</a> <a href="javascript:void(0)" ng-click="deleteStudent(s.id)">Delete</a></td>
    </tr>
  </tbody>
</table>

studentController.js

angular
    .module('studentInfoApp')
    .factory('Student', Student)
    .controller('StudentsController', StudentsController)
    .config(config);

function config($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'StudentsController',
        templateUrl: 'app/views/student-list.html'
    })
    .otherwise({
        redirectTo: '/'
    });
}

function Student($resource) {
    //return $resource('/students/:id');
    return $resource("/students/:id", {}, {
        'get':    {method:'GET'},
        'save':   {method:'POST'},
        'query':  {method:'GET', isArray:true},
        'remove': {method:'DELETE'},
        'delete': {method:'DELETE'}
    });
}

function StudentsController(Student, $scope, $http) {
$scope.editStudent = function(id) {
        Student.query({ id: id }, function(data, headers) {
            $scope.student = data;
            $scope.dataForm = true;
        }, function (error) {
            console.log(error);
        });

    }
}

The existing setup functions correctly, however, if I introduce an Angular model in an input element as shown below:

<input id="first_name" value="{{student[0].fname}}" type="text" class="validate" ng-model="editForm.fname">

the input value fails to render. Is there something crucial that I am overlooking here?

Answer №1

On the initial digest, the value of <input /> is replaced by the value of the variable linked to ng-model.

When you utilize ng-model, you establish a two-way binding mechanism. Angular ensures that the value of <input /> and the referenced variable stay in sync during each digest.

Instead of using the value attribute to set the initial value of your <input />, assign the desired initial value directly to the variable linked to ng-model.

Answer №2

The ng-model directive does the work of setting the value for you automatically. Simply delete the value in your HTML and assign ng-model to

<input id="last_name" type="text" class="validate" ng-model="person[0].lname">

Next time, it would be helpful to include a plunkr or jsfiddle link.

Thank you

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

A guide on implementing Google reCAPTCHA in a Nuxt.js website

Trying to implement the recaptcha-module from nuxt-community in my Nuxt project but struggling with verifying if the user has passed the check. The documentation and example provided are not clear enough for me (https://github.com/nuxt-community/recaptch ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...

Graph not displaying dates on the x-axis in flot chart

I've been attempting to plot the x-axis in a Flot chart with dates. I've tried configuring the x-axis and using JavaScript EPOCH, but have had no success so far. Here's a snippet of my code: <?php foreach($data[0] as $i => $d){ ...

Vue.js filters items based on their property being less than or equal to the input value

I'm currently working on a project in vue.js where I need to filter elements of an object based on a specific condition. I want to only return items where maxPeoples are greater than or equal to the input value. Below is a snippet of my code: model ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

Unset the class upon clicking outside the div, but maintain the class unset when the div is closed

I have a div that opens when the question mark icon in the upper right corner of the document is clicked. When clicked, a class is added which transforms the question mark into a close icon. When clicking outside the div, the div closes and the class is re ...

Encountered an error: Incorrect decomposition attempt on a non-iterable object

I have implemented a DataTable component using react-table. Below is the code for my component: const DataTable: React.FC<IDataTable<any>> = (props: IDataTable<any>) => { const { columns, data, className, rowSelection, onChange, ...r ...

A guide on implementing React hooks within a React class component

Just stepped into the JavaScript world and facing a bit of trouble... Currently, I'm working with a React hook import { useKeycloak } from '@react-keycloak/web'; import { useCallback } from 'react'; export const useAuthenticatedCal ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...

Setting an Element's attribute is only visible in the console

Just dipping my toes into the world of Web Development. While playing around with some JavaScript within HTML, I decided to try updating the content of an element. Upon running the code below, "Updated Content" appears in the console as intended. However, ...

To successfully process this file type in JavaScript, you might require a suitable loader

Currently, I am facing an issue with my MVC application while trying to integrate Bootstrap 5 using Webpack. Despite attempting various workarounds with stage-0, stage-2, and stage-3, none have proven successful for me. I suspect that the problem lies wit ...

Top Strategies for Conducting API Requests with StrongLoop LoopBack

Loopback models have been created for easy access via REST, and AngularJS is being utilized to make REST calls like the example below. $http.get('http://localhost:3000/api/staffs'). success(function (data, status, headers, config) { ...

Oops! There seems to be a problem with inserting an image using

I am trying to insert multiple images with a loop when clicked. The images are named "0.jpg","1.jpg","2.jpg" etc. To achieve this, I am using an array with all the elements: {name: '1', result: 1, prefecture: "city", photo1: "0.jpg"}, and my l ...

Calculate the total with the applied filters

My goal is to sum the data from the Number table after applying lookup filters. The current issue is that the sum remains fixed for all values and doesn't take into account the filter. Here's the JavaScript function I'm using to search and ...

What is the best way to dynamically load content as it enters the viewport using JavaScript or jQuery?

I have implemented a stunning animation to the h1 element using a function, but now I want the animation to trigger only when the h1 element enters the viewport as the user scrolls down. Currently, the animation occurs as soon as the page is loaded, even ...

Error: The value of 'v4' property is not defined and cannot be read

I am encountering an issue with Vue.js: vue.esm.js?efeb:628 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'v4' of undefined" found in ---> <AddTodo> at src/components/AddTodo.vue <App> at src/Ap ...

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

What is the best way to dynamically reference an HTML file based on the value of a JSON data description, using the description as the filename

Here I have created a sample file which is currently working fine. However, my requirement is to call the HTML elements from a separate file and only reference the external file name in the Description field. Is it possible to achieve this by specifying th ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...