有人可以向我解释为什么我在打印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>
答案 0 :(得分: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具有2路数据绑定,这意味着视图和控制器中的值始终保持同步,而不必来回传递。