The input value does not update in the controller when using AngularJS ng-model

Why is it that when I print out console.log($scope.inputvalue), the variable does not update with the values I enter in the input field?

Did I misunderstand the purpose of ng-model? If so, how can I pass a value from the view to the controller?

(function () {
'use strict';

angular.module('LunchCheck', [])
.controller('checkiftoomuch', ['$scope', checkiftoomuch]);

function checkiftoomuch($scope){
$scope.inputvalue = "";
console.log($scope.inputvalue);
}

})();
<!doctype html>
<html lang="en" ng-app="LunchCheck">
  <head>
    <title>Lunch Checker</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="app.js"></script>
    <link rel="stylesheet" href="styles/bootstrap.min.css">
    <style>
      .message { font-size: 1.3em; font-weight: bold; }
    </style>
  </head>
<body>
   <div class="container" ng-controller="checkiftoomuch">
     <h1>Lunch Checker</h1>

         <div class="form-group">
             <input id="lunch-menu"
             type="text"
             placeholder="list comma separated dishes you usually have for lunch"
             class="form-control"
             ng-model="inputvalue">
         </div>
         <div class="form-group">
             <button class="btn btn-default">Check If Too Much</button>
         </div>
         <div class="form-group message">
           Total number of disches: {{ inputvalue }}
         </div>
   </div>

</body>
</html>

Answer №1

Before logging using console.log, you're initializing $scope.inputvalue = "";. Remember to log the value again after making changes. Try this approach:

function checkiftoomuch($scope){
    $scope.inputvalue = "";
    console.log($scope.inputvalue);

    $scope.$watch('inputvalue', function(newValue, oldValue){
        console.log(newValue);
    })
}

You can also create a function for your button click event like:

<div class="form-group">
    <button class="btn btn-default" ng-click="showValue()>Check If Too Much</button>
</div>

In your JS file:

function checkiftoomuch($scope){
    $scope.inputvalue = "";
    console.log($scope.inputvalue);

    $scope.showValue = function(){
        console.log($scope.inputvalue);
    }
}

AngularJS offers 2-way data binding, ensuring that values in the view and controller remain synced without needing constant passing back and forth.

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

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Adhesive Navigation Bar

Check out this link: JSFIDDLE $('.main-menu').addClass('fixed'); Why does the fixed element flicker when the fixed class is applied? ...

What is the method for executing a server-side script without it being transmitted to the browser in any way?

Although the title may be misleading, my goal is to have my website execute a php file on the server side using arguments extracted from the html code. For example: document.getElementById("example").value; I want to run this operation on the se ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

Linking chained functions for reuse of code in react-redux through mapStateToProps and mapDispatchToProps

Imagine I have two connected Redux components. The first component is a simple todo loading and display container, with functions passed to connect(): mapStateToProps reads todos from the Redux state, and mapDispatchToProps requests the latest list of todo ...

Converting JSON data types into TypeScript interface data types

Struggling to convert data types to numbers using JSON.parse and the Reviver function. I've experimented with different options and examples, but can't seem to figure out where I'm going wrong. The Typescript interface I'm working with ...

Browserify Rails encountered an error - ParseError: Error with 'import' and 'export'. These statements can only appear with 'sourceType: module'

Recently, I encountered an issue while trying to integrate an NPM package into my Rails application. The problem I'm facing can be seen in the following image: https://i.stack.imgur.com/cIOw8.png I searched this forum for similar issues but found tha ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

What is the method for retrieving post ID with the Google Feed API?

I am currently utilizing two different JS codes to dynamically load posts from my Wordpress website: Code 1: JSON API <script src="http://howtodeployit.com/category/daily-devotion/?json=recentstories&callback=listPosts" type="text/javascript">& ...

What is the best way to determine the width and height of text within a TextArea using JavaScript in an HTML document

Imagine this scenario: https://i.stack.imgur.com/cliKE.png I am looking to determine the size of the red box within the textarea. Specifically, I want to measure the dimensions of the text itself, not the dimensions of the entire textarea. The HTML code ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

The process on how to access dynamic object properties within a parent component while using v-for in a child component

I am working on a child component that utilizes v-for to loop through data. Below is the code for the child component: <template> <div> <ul> <li v-for="item in listItems" :key=item.id&g ...

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

The scrolltop animation does not appear to be functioning properly on iOS devices

I have implemented a JavaScript effect to increase the line-height of each list item on my website as you scroll. It works perfectly on my Macbook and Android Smartphone, but for some reason, it's not working on an iPhone. Can anyone provide a solutio ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

Is it more efficient to use Vue events or Vuex for transmitting data between components?

Working on a project where data needs to be shared between components in order to update a canvas element at 30-60fps for optimal performance on low-end devices. Currently utilizing Vuex store/get method for data transfer, but considering using events as ...

What techniques can be employed to utilize multiple JavaScript files?

Hey there, I am facing an issue while trying to execute multiple JavaScript codes. My first script is running smoothly with the change function, but the second one seems to be causing some trouble. Can anyone guide me on how to effectively run multiple J ...