数据绑定在带有输入标签的 AngularJS 中不起作用
Data binding not working in AngularJS with input tag
下面是我的 angularjs 代码,
当我尝试在文本框中输入任何文本时,它不会出现在绑定中。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('cont', ['$scope', function($scope) {
}]);
</script>
</head>
<body ng-app="myApp">
<input type="text" ng-bind="user"></input>
<p>{{user}}</p>
</body>
</html>
您需要使用 ng-model
directive for 2-way binding. ng-bind
is just one-way which updates the bound element with data (model value) when a digest cycle happens. Without ng-model when you update the textbox there wont be any digest cycle. Angular has directive definition for types like input
and other form controls which requires optional ng-model
directive. And these element directives registers events like change/input
etc only if it gets the optional ng-model controller on the target element. And when you have them it uses ng-model controller to set the view-value, model-value and triggers the digest cycle when that event occurs. Of course with the new angular versions there is an ng-model-options
,您可以在元素级别或全局级别设置它来指定您希望模型值更新(和表单验证)何时发生。
也一样:-
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
虽然您的情况不是问题,但您缺少 ng-controller="cont"
的用法。如果没有它,所有属性都将附加到您的情况下的 rootScope。所以可能是:
<body ng-app="myApp">
<div ng-controller="cont">
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
</div>
</body>
下面是我的 angularjs 代码, 当我尝试在文本框中输入任何文本时,它不会出现在绑定中。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="js/angular.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('cont', ['$scope', function($scope) {
}]);
</script>
</head>
<body ng-app="myApp">
<input type="text" ng-bind="user"></input>
<p>{{user}}</p>
</body>
</html>
您需要使用 ng-model
directive for 2-way binding. ng-bind
is just one-way which updates the bound element with data (model value) when a digest cycle happens. Without ng-model when you update the textbox there wont be any digest cycle. Angular has directive definition for types like input
and other form controls which requires optional ng-model
directive. And these element directives registers events like change/input
etc only if it gets the optional ng-model controller on the target element. And when you have them it uses ng-model controller to set the view-value, model-value and triggers the digest cycle when that event occurs. Of course with the new angular versions there is an ng-model-options
,您可以在元素级别或全局级别设置它来指定您希望模型值更新(和表单验证)何时发生。
也一样:-
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
虽然您的情况不是问题,但您缺少 ng-controller="cont"
的用法。如果没有它,所有属性都将附加到您的情况下的 rootScope。所以可能是:
<body ng-app="myApp">
<div ng-controller="cont">
<input type="text" ng-model="user" name="user"></input>
<p>{{user}}</p>
</div>
</body>