据我了解,ng-model 为分配模型的特定元素设置值。鉴于 ng-value 与 ng-model 有何不同?
5 回答
它与 ng-model 结合使用;对于 radios 和 selects,它是在选择该项目时设置为 ng-model 的值。将其用作元素的“值”属性的替代品,该属性将始终将字符串值存储到关联的 ng-model。
在单选按钮的上下文中,它允许您使用非字符串值。例如,如果您有单选按钮“是”和“否”(或等效),其值为“真”和“假” - 如果您使用“值”,则存储在 ng-model 中的值将变为字符串。如果您使用“ng-value”,它们将保持为布尔值。
但是,在 select 元素的上下文中,请注意 ng-value 仍将始终被视为字符串。要为选择设置非字符串值,请使用 ngOptions。
简单说明
ng模型
- 用于变量的两种方式绑定,可以在范围和 html 上使用。
- 它具有
$modelValue
(值驻留在实际范围内)和$viewValue
(显示在视图上的值)。 - 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
- Is used to assign value to respective
ng-model
value likeinput
,select
&textarea
(same can be done by usingng-init
) ng-value
does provide good binding if your are settingng-model
value through ajax while writingvalue
attribute doesn't support it- Basically meant to use for
radio
&option
tag while creatingselect
options dynamically. - 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>
...
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.
根据https://docs.angularjs.org/api/ng/directive/ngValue,ngValue采用“角度表达式,其值将绑定到输入元素的 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 控件(输入、选择、文本区域)的值绑定到应用程序数据。
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 atextarea
, when that element does not usengModel
.
Instead, initialize the value from the controller: