【发布时间】:2019-02-27 10:39:35
【问题描述】:
谁能向我解释为什么当我打印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>
【问题讨论】:
-
“只要你有 ng-model,就一定会有一个点。如果你没有一个点,那你就做错了。” .您的问题是您正在编辑的 inputValue 在子指令范围内,而不是您的控制器的范围内。你必须把你的输入放在像
$scope.state = { inputValue : 0 }这样的对象中并使用ng-model="state.inputValue" -
@PierreEmmanuelLallemant - 我想在这里有所不同,总是可以使用直接附加到范围的变量,而不将其设为对象属性。
inputValue肯定在控制器的范围内。 -
@AnuragSrivastava 不,你不能。最好的方法是使用controllerAs:在指令声明中使用
'controllerAs': '$ctrl',在控制器中使用this.inputValue而不是$scope.inputValue,在视图中使用ng-model="$ctrl.inputValue"。它不会在 $scope 中,只是附加到控制器的this上。 -
@PierreEmmanuelLallemant 你运行上面提供的代码 sn-p 了吗?视图在不使用任何对象或
controllerAs语法的情况下更新。 -
没有读过你的代码,看来你还有问题。但无论如何,如果您在输入周围使用指令(ng-if 等...),您的
ngmodel="inputvalue"将成为问题,因为会有一个新的范围,在这种情况下,来自控制器的 $scope.inputvalue 将不会返回显示的价值。
标签: javascript angularjs input angularjs-ng-model