本文翻译自:What's the difference between ng-model and ng-bind
I'm currently learning AngularJS and am having difficulty understanding the difference between ng-bind
and ng-model
. 我目前正在学习AngularJS,并且很难理解ng-bind
和ng-model
之间的区别。
Can anyone tell me how they differ and when one should be used over the other? 任何人都可以告诉我他们的差异,以及何时应该使用另一个?
#1楼
参考:https://stackoom.com/question/q6uR/ng-model和ng-bind之间有什么区别
#2楼
ng-bind has one-way data binding ($scope --> view). ng-bind具有单向数据绑定($ scope - > view)。 It has a shortcut {
{ val }}
which displays the scope value $scope.val
inserted into html where val
is a variable name. 它有一个快捷方式{
{ val }}
,它显示插入到html中的范围值$scope.val
,其中val
是一个变量名。
ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) eg <input ng-model="val"/>
. ng-model旨在放在表单元素内,并具有双向数据绑定($ scope - > view和view - > $ scope),例如<input ng-model="val"/>
。
#3楼
tosh 's answer gets to the heart of the question nicely. 托什的回答很好地解决了问题的核心。 Here's some additional information.... 这是一些额外的信息....
Filters & Formatters 过滤器和格式化程序
ng-bind
and ng-model
both have the concept of transforming data before outputting it for the user. ng-bind
和ng-model
都具有在为用户输出数据之前转换数据的概念。 To that end, ng-bind
uses filters , while ng-model
uses formatters . 为此, ng-bind
使用过滤器 ,而ng-model
使用格式化程序 。
filter (ng-bind) 过滤器(ng-bind)
With ng-bind
, you can use a filter to transform your data. 使用ng-bind
,您可以使用过滤器来转换数据。 For example, 例如,
<div ng-bind="mystring | uppercase"></div>
, <div ng-bind="mystring | uppercase"></div>
,
or more simply: 或更简单地说:
<div>{
{mystring | uppercase}}</div>
Note that uppercase
is a built-in angular filter , although you can also