Furin
Furin

Reputation: 582

Angularjs ng-model in input does not update value in controller

Can anyone explain to me why when I print console.log($scope.inputvalue) the variable is not updated with the values that I enter in the input?

Maybe I just misunderstood the meaning of ng-model, in this case, how do I pass a value from the view to 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>

Upvotes: 1

Views: 2406

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

You're setting $scope.inputvalue = ""; before the console.log. But after you change the value, you need to console.log it again. Try using:

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

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

Or add a function on your button click like:

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

And in JS:

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

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

AngularJS has 2-way data binding which means, the values in the view and controller are in sync always, they do not have to be passed back and forth.

Upvotes: 1

Related Questions