44

据我了解,ng-model 为分配模型的特定元素设置值。鉴于 ng-value 与 ng-model 有何不同?

4

5 回答 5

29

它与 ng-model 结合使用;对于 radios 和 selects,它是在选择该项目时设置为 ng-model 的值。将其用作元素的“值”属性的替代品,该属性将始终将字符串值存储到关联的 ng-model。

在单选按钮的上下文中,它允许您使用非字符串值。例如,如果您有单选按钮“是”和“否”(或等效),其值为“真”和“假” - 如果您使用“值”,则存储在 ng-model 中的值将变为字符串。如果您使用“ng-value”,它们将保持为布尔值。

但是,在 select 元素的上下文中,请注意 ng-value 仍将始终被视为字符串。要为选择设置非字符串值,请使用 ngOptions。

于 2015-02-25T11:17:30.047 回答
15

简单说明

ng模型

  1. 用于变量的两种方式绑定,可以在范围和 html 上使用。
  2. 它具有$modelValue(值驻留在实际范围内)和$viewValue(显示在视图上的值)。
  3. If you mentioned on form with name attribute then angular internally creates validation attributes for it like $error, $valid, $invalid etc.

Eg.

<input type="text/checkbox/radio/number/tel/email/url" ng-model="test"/>

ng-value

  1. Is used to assign value to respective ng-model value like input, select & textarea(same can be done by using ng-init)
  2. ng-value does provide good binding if your are setting ng-model value through ajax while writing value attribute doesn't support it
  3. Basically meant to use for radio & option tag while creating select options dynamically.
  4. It can only have string value it, it doesn't support object value.

HTML

<input
  [ng-value="string"]>
...
</input>

OR

<select ng-model="selected">
  <option ng-value="option.value" ng-repeat="option in options">
     {{option.name}}
  </option>
</select>

...

于 2015-02-25T11:41:48.930 回答
3

A good use for ng-value in input fields is if you want to bind to a variable, but based on another variable's value. Example:

<h1>The code is {{model.code}}.</h1>
<p>Set the new code: <input type="text" ng-bind="model.code" /></p>

When the user types in the input, the value in the title will be updated. If you don't want this, you can modify to:

<input type="text" ng-value="model.code" ng-bind="model.theNewCode" />

theNewCode will be updated, but code will remain untouched.

于 2016-07-28T17:51:43.593 回答
2

根据https://docs.angularjs.org/api/ng/directive/ngValuengValue采用“角度表达式,其值将绑定到输入元素的 value 属性”。

因此,当您使用 ng-value="hard" 时,它被解释为一个表达式,并且该值绑定到 $scope.hard (可能未定义)。ngValue 对于评估表达式很有用——它对设置硬编码值的 value 没有优势。然而,如果你想用 ngValue 硬编码一个值,你必须将它括在 '' 中:

ng-value="'hard'"

ng-model旨在放置在表单元素中,并具有双向数据绑定($scope --> view 和 view --> $scope),例如<input ng-model="val"/>.

或者您可以说ng-model指令将 HTML 控件(输入、选择、文本区域)的值绑定到应用程序数据。

于 2015-02-25T11:16:25.320 回答
0

The documentation clearly states that ng-value should not be used when doing two-way binding with ng-model.

From the Docs:

ngValue

Binds the given expression to the value of the element.

It can also be used to achieve one-way binding of a given expression to an input element such as an input[text] or a textarea, when that element does not use ngModel.

AngularJS ng-value Directive API Reference

Instead, initialize the value from the controller:

于 2019-07-26T18:27:06.990 回答