[英]AngularJS two-way binding
I am having problems with two-way binding in AngularJS
.我在
AngularJS
中遇到双向绑定问题。 In my HTML
, I have:在我的
HTML
,我有:
<div class="row" ng-app="creation">
<form class="form-horizontal" ng-controller="CreationController as cCtrl" ng-submit="cCtrl.send()" novalidate>
<div class="form-group">
<label class="col-sm-4">Model</label>
<div class="col-sm-8">
<input class="form-control" type="text" ng-model="cCtrl['data']['model']" id="model" />
</div>
</div>
...
On the JavaScript
side, I have:在
JavaScript
方面,我有:
(function() {
var app = angular.module('creation', ['validation', 'link']);
app.controller('CreationController', ['$scope', function($scope) {
$scope.data = {};
$scope.data.model = 'hello';
...
Why is $scope.data.model
not displaying hello when I render the HTML
page?为什么在呈现
HTML
页面时$scope.data.model
不显示hello ? Instead it is displaying nothing, and when I finally entering something in the input field, it updates $scope.data.model
.相反,它什么也不显示,当我最终在输入字段中输入内容时,它会更新
$scope.data.model
。
This is because you're setting your data model on the $scope
but in your html you're referencing under cCtrl
which is a controller instance.这是因为您在
$scope
上设置数据模型,但在您的 html 中,您在cCtrl
下引用,这是一个控制器实例。 Try just using ng-model=data.model
in your html.尝试在您的 html 中使用
ng-model=data.model
。
Actually that ' Controller as ' syntax can be very useful and easy to follow.实际上,' Controller as ' 语法非常有用且易于遵循。 I would prefer to keep that because you can isolate the data as you want and work with it in a cleaner way.
我更愿意保留它,因为您可以根据需要隔离数据并以更清晰的方式使用它。
The problem with your code is that you have to bind the data object to this , not to the $scope您的代码的问题在于您必须将数据对象绑定到this ,而不是$scope
(function() {
var app = angular.module('creation', ['validation', 'link']);
app.controller('CreationController', [function() {
// You can use an object to refer to *this* (vm stands for 'ViewModel').
var vm = this;
vm.data = {};
vm.data.model = 'hello';
// or just have vm.data = {model: 'hello'};
...
and then use it in the template like you've used it.然后像使用它一样在模板中使用它。
More than that you do not have to inject the $scope** unless you want to use something specific from angular like digest or watch, or inherit from parent scopes/parent controllers.更重要的是你,除非你想用什么具体的角像摘要或手表,或从父项继承范围/母控制器没有注入$范围**。
Here is also a nice style guide for angular that explains other concepts also: Angular Style Guide这也是一个很好的 angular 风格指南,它也解释了其他概念: Angular Style Guide
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.