ng模型和ng-bind有什么区别?

时间:2021-08-24 20:06:03

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?

谁能告诉我它们是怎样不同的,什么时候应该用在另一个上?

8 个解决方案

#1


791  

ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

ng绑定具有单向数据绑定($scope——>视图)。它有一个快捷方式{{val},它显示范围值$scope。val插入到html中,val是一个变量名。

ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

ng模型的目的是将表单元素放入表单元素中,并具有双向数据绑定($scope——>视图和视图——> $scope),例如:

#2


138  

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. To that end, ng-bind uses filters, while ng-model uses formatters.

ng-bind和ng模型在输出数据之前都有转换数据的概念。为此,ng绑定使用过滤器,而ng模型使用格式化程序。

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

使用ng-bind,您可以使用一个过滤器来转换您的数据。例如,

<div ng-bind="mystring | uppercase"></div>,

< div ng-bind = " mystring |大写" > < / div >,

or more simply:

或者更简单:

<div>{{mystring | uppercase}}</div>

< div > { { mystring |大写} } < / div >

Note that uppercase is a built-in angular filter, although you can also build your own filter.

注意,大写字母是一个内置的角过滤器,尽管您也可以构建自己的过滤器。

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

要创建一个ng模型格式化程序,您需要创建一个需要“ngModel”的指令,该指令允许该指令访问ngModel的控制器。例如:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

然后在你的部分:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.

这本质上是一个ng模型,就像上面的ng-bind例子所做的那样。


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

现在,如果您打算允许用户更改mystring的值,该怎么办?ng-bind只有单向绑定,从模型->视图。但是,ng模型可以从视图->模型中绑定,这意味着您可以允许用户更改模型的数据,并且使用解析器可以以一种简化的方式格式化用户的数据。这是它的样子:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples

使用ng模型格式化程序/解析器示例的活动插入器。


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

ng模型也有内置的验证。只需修改您的$解析器或$formatters函数,就可以调用ngModel的控制器。美元setValidity(validationErrorKey isValid)函数。

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

角1.3有一个新的$validators数组,您可以使用它来验证,而不是$解析器或$格式化程序。

Angular 1.3 also has getter/setter support for ngModel

角1.3还为ngModel提供了getter/setter支持。

#3


29  

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

此指令在优先级别1执行。

Example Plunker

例子恰好

JAVASCRIPT

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

ngModel负责:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • 将视图绑定到模型中,其他指令如输入、textarea或select require。
  • Providing validation behavior (i.e. required, number, email, url).
  • 提供验证行为(即要求、编号、电子邮件、url)。
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • 保持控件状态(有效/无效、脏/原始、触摸/未修改、验证错误)。
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • 在元素上设置相关的css类(ng-valid, ng-invalid, ng-dirty, ng-, ng-touch, ng-touch),包括动画。
  • Registering the control with its parent form.
  • 以其父窗体注册控件。

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

此指令在优先级0执行。

Example Plunker

例子恰好

JAVASCRIPT

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

ngBind负责:

  • Replacing the text content of the specified HTML element with the value of a given expression.
  • 用给定表达式的值替换指定HTML元素的文本内容。

#4


8  

If you are hesiting between using ng-bind or ng-model, try to answer these questions:

如果你正在使用ng-bind或ng模型,试着回答以下问题:


Do you only need to display data?

你只需要显示数据吗?

  • Yes: ng-bind (one-way binding)

    是的:ng-bind(单向绑定)

  • No: ng-model (two-way binding)

    没有:ng-model(双向绑定)

Do you need to bind text content (and not value)?

是否需要绑定文本内容(而不是值)?

  • Yes: ng-bind

    是的:ng-bind

  • No: ng-model (you should not use ng-bind where value is required)

    不:ng模型(你不应该在需要值的地方使用ng-bind)

Is your tag a HTML <input>?

你的标签是HTML <输入> 吗?

  • Yes: ng-model (you cannot use ng-bind with input tag)

    是的:ng模型(不能使用输入标记的ng绑定)

  • No: ng-bind

    没有:ng-bind

#5


6  

ng-model

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

在AngularJS中,ng模型指令是将应用程序中使用的变量与输入组件绑定在一起的最大力量之一。这是双向数据绑定。如果您想更好地理解这两种方法绑定,那么您有一个输入组件,并且更新到该字段的值必须反映在应用程序的其他部分。更好的解决方案是将一个变量绑定到该字段,并输出您希望通过oput显示更新的值的变量。

ng-bind

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

ng-bind的工作方式与ng模型大不相同。ng-bind是一种数据绑定,用于将html组件内的值显示为内部html。该指令不能用于与变量绑定,但只能与HTML元素内容绑定。事实上,这可以与ng模型一起使用,以将组件绑定到HTML元素。这个指令对于用内部HTML内容更新div、span等块是非常有用的。

This example would help you to understand.

这个例子可以帮助你理解。

#6


5  

angular.module('testApp',[]).controller('testCTRL',function($scope)
                               
{
  
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";            
});
div input{
width:600px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<head>Diff b/w model and bind</head>
<body data-ng-app="testApp">
    <div data-ng-controller="testCTRL">
        Model-Data : <input type="text" data-ng-model="testingModel">
        <p>{{testingModel}}</p>
          <input type="text" data-ng-bind="testingBind">
          <p ng-bind="testingBind"></p>
    </div>
</body>

#7


2  

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

ngModel通常用于绑定一个变量的输入标签,我们可以从控制器和html页面改变变量,但是ngBind用于在html页面中显示一个变量,我们可以从控制器和html仅显示变量来改变变量。

#8


1  

We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

我们可以使用ng-bind与

来显示,我们可以使用ng-bind {{model}}的快捷方式,我们不能用html输入控件来使用ng-bind,但是我们可以使用html输入控件的ng-bind {{model}}的快捷方式。

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>

#1


791  

ng-bind has one-way data binding ($scope --> view). It has a shortcut {{ val }} which displays the scope value $scope.val inserted into html where val is a variable name.

ng绑定具有单向数据绑定($scope——>视图)。它有一个快捷方式{{val},它显示范围值$scope。val插入到html中,val是一个变量名。

ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.

ng模型的目的是将表单元素放入表单元素中,并具有双向数据绑定($scope——>视图和视图——> $scope),例如:

#2


138  

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. To that end, ng-bind uses filters, while ng-model uses formatters.

ng-bind和ng模型在输出数据之前都有转换数据的概念。为此,ng绑定使用过滤器,而ng模型使用格式化程序。

filter (ng-bind)

With ng-bind, you can use a filter to transform your data. For example,

使用ng-bind,您可以使用一个过滤器来转换您的数据。例如,

<div ng-bind="mystring | uppercase"></div>,

< div ng-bind = " mystring |大写" > < / div >,

or more simply:

或者更简单:

<div>{{mystring | uppercase}}</div>

< div > { { mystring |大写} } < / div >

Note that uppercase is a built-in angular filter, although you can also build your own filter.

注意,大写字母是一个内置的角过滤器,尽管您也可以构建自己的过滤器。

formatter (ng-model)

To create an ng-model formatter, you create a directive that does require: 'ngModel', which allows that directive to gain access to ngModel's controller. For example:

要创建一个ng模型格式化程序,您需要创建一个需要“ngModel”的指令,该指令允许该指令访问ngModel的控制器。例如:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$formatters.push(function(value) {
        return value.toUpperCase();
      });
    }
  }
}

Then in your partial:

然后在你的部分:

<input ngModel="mystring" my-model-formatter />

This is essentially the ng-model equivalent of what the uppercase filter is doing in the ng-bind example above.

这本质上是一个ng模型,就像上面的ng-bind例子所做的那样。


Parsers

Now, what if you plan to allow the user to change the value of mystring? ng-bind only has one way binding, from model-->view. However, ng-model can bind from view-->model which means that you may allow the user to change the model's data, and using a parser you can format the user's data in a streamlined manner. Here's what that looks like:

现在,如果您打算允许用户更改mystring的值,该怎么办?ng-bind只有单向绑定,从模型->视图。但是,ng模型可以从视图->模型中绑定,这意味着您可以允许用户更改模型的数据,并且使用解析器可以以一种简化的方式格式化用户的数据。这是它的样子:

app.directive('myModelFormatter', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, controller) {
     controller.$parsers.push(function(value) {
        return value.toLowerCase();
      });
    }
  }
}

Play with a live plunker of the ng-model formatter/parser examples

使用ng模型格式化程序/解析器示例的活动插入器。


What Else?

ng-model also has built-in validation. Simply modify your $parsers or $formatters function to call ngModel's controller.$setValidity(validationErrorKey, isValid) function.

ng模型也有内置的验证。只需修改您的$解析器或$formatters函数,就可以调用ngModel的控制器。美元setValidity(validationErrorKey isValid)函数。

Angular 1.3 has a new $validators array which you can use for validation instead of $parsers or $formatters.

角1.3有一个新的$validators数组,您可以使用它来验证,而不是$解析器或$格式化程序。

Angular 1.3 also has getter/setter support for ngModel

角1.3还为ngModel提供了getter/setter支持。

#3


29  

ngModel

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.

This directive executes at priority level 1.

此指令在优先级别1执行。

Example Plunker

例子恰好

JAVASCRIPT

JAVASCRIPT

angular.module('inputExample', [])
   .controller('ExampleController', ['$scope', function($scope) {
     $scope.val = '1';
}]);

CSS

CSS

.my-input {
    -webkit-transition:all linear 0.5s;
    transition:all linear 0.5s;
    background: transparent;
}
.my-input.ng-invalid {
    color:white;
    background: red;
}

HTML

HTML

<p id="inputDescription">
   Update input to see transitions when valid/invalid.
   Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
    <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
         aria-describedby="inputDescription" />
</form>

ngModel is responsible for:

ngModel负责:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • 将视图绑定到模型中,其他指令如输入、textarea或select require。
  • Providing validation behavior (i.e. required, number, email, url).
  • 提供验证行为(即要求、编号、电子邮件、url)。
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • 保持控件状态(有效/无效、脏/原始、触摸/未修改、验证错误)。
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched) including animations.
  • 在元素上设置相关的css类(ng-valid, ng-invalid, ng-dirty, ng-, ng-touch, ng-touch),包括动画。
  • Registering the control with its parent form.
  • 以其父窗体注册控件。

ngBind

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

This directive executes at priority level 0.

此指令在优先级0执行。

Example Plunker

例子恰好

JAVASCRIPT

JAVASCRIPT

angular.module('bindExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
    $scope.name = 'Whirled';
}]);

HTML

HTML

<div ng-controller="ExampleController">
  <label>Enter name: <input type="text" ng-model="name"></label><br>
  Hello <span ng-bind="name"></span>!
</div>

ngBind is responsible for:

ngBind负责:

  • Replacing the text content of the specified HTML element with the value of a given expression.
  • 用给定表达式的值替换指定HTML元素的文本内容。

#4


8  

If you are hesiting between using ng-bind or ng-model, try to answer these questions:

如果你正在使用ng-bind或ng模型,试着回答以下问题:


Do you only need to display data?

你只需要显示数据吗?

  • Yes: ng-bind (one-way binding)

    是的:ng-bind(单向绑定)

  • No: ng-model (two-way binding)

    没有:ng-model(双向绑定)

Do you need to bind text content (and not value)?

是否需要绑定文本内容(而不是值)?

  • Yes: ng-bind

    是的:ng-bind

  • No: ng-model (you should not use ng-bind where value is required)

    不:ng模型(你不应该在需要值的地方使用ng-bind)

Is your tag a HTML <input>?

你的标签是HTML <输入> 吗?

  • Yes: ng-model (you cannot use ng-bind with input tag)

    是的:ng模型(不能使用输入标记的ng绑定)

  • No: ng-bind

    没有:ng-bind

#5


6  

ng-model

ng-model

ng-model directive in AngularJS is one of the greatest strength to bind the variables used in application with input components. This works as two way data binding. If you want to understand better about the two way bindings, you have an input component and the value updated into that field must be reflected in other part of the application. The better solution is to bind a variable to that field and output that variable whereever you wish to display the updated value throughoput the application.

在AngularJS中,ng模型指令是将应用程序中使用的变量与输入组件绑定在一起的最大力量之一。这是双向数据绑定。如果您想更好地理解这两种方法绑定,那么您有一个输入组件,并且更新到该字段的值必须反映在应用程序的其他部分。更好的解决方案是将一个变量绑定到该字段,并输出您希望通过oput显示更新的值的变量。

ng-bind

ng-bind

ng-bind works much different than ng-model. ng-bind is one way data binding used for displaying the value inside html component as inner HTML. This directive can not be used for binding with the variable but only with the HTML elements content. Infact this can be used along with ng-model to bind the component to HTML elements. This directive is very useful for updating the blocks like div, span, etc. with inner HTML content.

ng-bind的工作方式与ng模型大不相同。ng-bind是一种数据绑定,用于将html组件内的值显示为内部html。该指令不能用于与变量绑定,但只能与HTML元素内容绑定。事实上,这可以与ng模型一起使用,以将组件绑定到HTML元素。这个指令对于用内部HTML内容更新div、span等块是非常有用的。

This example would help you to understand.

这个例子可以帮助你理解。

#6


5  

angular.module('testApp',[]).controller('testCTRL',function($scope)
                               
{
  
$scope.testingModel = "This is ModelData.If you change textbox data it will reflected here..because model is two way binding reflected in both.";
$scope.testingBind = "This is BindData.You can't change this beacause it is binded with html..In above textBox i tried to use bind, but it is not working because it is one way binding.";            
});
div input{
width:600px;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<head>Diff b/w model and bind</head>
<body data-ng-app="testApp">
    <div data-ng-controller="testCTRL">
        Model-Data : <input type="text" data-ng-model="testingModel">
        <p>{{testingModel}}</p>
          <input type="text" data-ng-bind="testingBind">
          <p ng-bind="testingBind"></p>
    </div>
</body>

#7


2  

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.

ngModel通常用于绑定一个变量的输入标签,我们可以从控制器和html页面改变变量,但是ngBind用于在html页面中显示一个变量,我们可以从控制器和html仅显示变量来改变变量。

#8


1  

We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

我们可以使用ng-bind与

来显示,我们可以使用ng-bind {{model}}的快捷方式,我们不能用html输入控件来使用ng-bind,但是我们可以使用html输入控件的ng-bind {{model}}的快捷方式。

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>