我是一个新手,试图理解有角度的双向数据绑定。在文档https://docs.angularjs.org/guide/databinding中,它提到“对视图的任何更改都会立即反映在模型中,并且模型中的任何更改都会传播到视图”。因此,如果有一个输入框(模型)和一个表达式(视图),我可以看到“模型中的任何更改都传播到视图”有效,但我想看一个相反场景的示例,即。 “对视图的任何更改都会立即反映在模型中”,我该如何自我展示。任何帮助都会受到高度评价。谢谢
4 回答
请参阅此工作代码JsFiddle
$watch 将监视变量(ng-model)在这种情况下的任何更改并调用该函数。即使不添加 $watch,您在输入框中输入的任何内容都会在后端自动更新。$watch 是检查模型是否正确更新的一种方法。
单击登录按钮时,最新的模型值将出现在控制器中。
$scope.$watch('user.firstName',function(){
alert("Your name is changed to : "+$scope.user.firstName);
});
在这个 angularjs 的基本示例中,我们使用了一个指令 ng-model。它具有双向数据绑定($scope --> view 和 view --> $scope)。$scope 是一个对象,它为绑定到它的每个对象维护一个数组 $$watchers,并且该数组中的每个对象都有一个键'last' 存储模型中最后更新的值。
<div ng-app>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</div>
在这种情况下,“yourName”模型与 $scope 绑定。因此,angularjs 在内部使用 $watch 查找此模型中的更改,并且摘要循环立即将所有更改更新到视图
$watch(watchExpression, listener, [objectEquality]);//Registers a listener callback to be executed whenever the watchExpression changes.
$digest();//Processes all of the watchers of the current scope and its children.
您还可以在角度控制器中查找模型的变化
$scope.$watch('yourName',function(){
//do your stuff when the model changes
});
您会看到,如果您更改视图,即您的输入框,ng-model 中定义的模型会更改,并且此更改的模型会反映回视图。
Angular中的两种方式数据绑定:
它帮助用户将数据从组件传递到视图以及从视图传递到组件。所以这将建立“双向通信”。
这可以通过 [(ngModel)] 实现,也称为“香蕉盒语法”,请参阅下面的代码片段以使用:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Enter the value : <input [(ngModel)] ='val'>
<br>
Entered value is: {{val}}
`
})
export class AppComponent {
val: string = '';
}
将 FormsModule 导入 app.module.ts 以避免在使用 ngModel 时出现模板解析错误:
import { FormsModule } from "@angular/forms";
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [ AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
我希望这很清楚。