输入中的Angularjs ng-model不会更新控制器中的值

问题描述 投票:0回答:1

任何人都可以向我解释为什么当我打印console.log($scope.inputvalue)时,变量没有更新我在input中输入的值?

也许我只是误解了ng-model的含义,在这种情况下,我如何将视图中的值传递给控制器​​?

(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>
javascript angularjs input angularjs-ng-model
1个回答
1
投票

你在$scope.inputvalue = "";之前设置console.log。但是在更改了值之后,你需要再次使用console.log。尝试使用:

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

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

或者在按钮上添加一个功能点击:

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

在JS中:

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

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

AngularJS具有双向数据绑定,这意味着视图和控制器中的值始终同步,它们不必来回传递。

© www.soinside.com 2019 - 2024. All rights reserved.