You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS:如何在ng-repeat中使用ng-default设置表单默认值?

Setting Default Values for Inputs in AngularJS ng-repeat

Hey there! Quick heads-up first: AngularJS doesn’t have an ng-default directive out of the box. But don’t worry—we’ve got a few straightforward ways to set default values for your inputs when looping with ng-repeat, based on the _text property in your JSON data.

Option 1: Bind to a Model (Two-Way Binding)

This is the most flexible approach if you need to track changes to the input value.

First, in your controller, extend each item in ValueArr with a model property initialized from its _text value:

// Process your input array to add a model property
$scope.ValueArr = yourJsonValues.map(item => {
  return {
    ...item,
    // Use _text as default if it exists, else empty string
    model: item._text || ''
  };
});

(If you’re dealing with numbers like data.concurrent, convert the value to a number: model: item._text ? Number(item._text) : 0)

Then update your HTML to bind the input to this new model property:

<b style="padding-top:5px;">&nbsp;Comments:</b> 
<span class="input">
  <input class="inputtxt" type="text" 
         ng-repeat="x in ValueArr" 
         ng-if="x._attributes.name === 'data.comments'"
         ng-model="x.model" />
</span>

Now the input will load with the _text value as the default, and any changes the user makes will be stored in x.model.

Option 2: Static Default with value Attribute

If you don’t need two-way binding (just a static default that doesn’t update the original data), use the value attribute with Angular interpolation:

<b style="padding-top:5px;">&nbsp;Comments:</b> 
<span class="input">
  <input class="inputtxt" type="text" 
         ng-repeat="x in ValueArr" 
         ng-if="x._attributes.name === 'data.comments'"
         value="{{x._text || ''}}" />
</span>

This will set the initial value, but user input won’t affect your original ValueArr items.

Option 3: Initialize Model with ng-init

If you prefer to keep the initialization in the HTML instead of the controller, use ng-init:

<b style="padding-top:5px;">&nbsp;Comments:</b> 
<span class="input">
  <input class="inputtxt" type="text" 
         ng-repeat="x in ValueArr" 
         ng-if="x._attributes.name === 'data.comments'"
         ng-init="x.model = x._text || ''"
         ng-model="x.model" />
</span>

This does the same as Option 1 but handles the model setup directly in the template.

Quick Tip:

Make sure your ng-if condition correctly targets the right item—I filled it in to check for data.comments since that’s the input you referenced, but adjust it as needed for other fields!

内容的提问来源于stack exchange,提问作者usersam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:19:06