AngularJS: ng-model动态绑定不起作用

AngularJS : ng-model dynamic binding does not work

本文关键字:不起作用 动态绑定 ng-model AngularJS      更新时间:2023-09-26

由于某些原因,我无法将下面的2种方式绑定。我正在尝试用一种动态的方式在表单

中填充ng模型。html:

<thead ng-repeat="field in fields">
<tr>
    <th>
        <select ng-model="{{field.day}}"></select> 
    </th>
    <th>
        <select ng-model="{{field.month}}"></select>
    </th>
    <th>
        <select ng-model="{{field.morning}}"></select>
    </th>
    <th>
        <select ng-model="{{field.eveningOpen}}"></select>
    </th>
    <th>
        <select ng-model="{{field.eveningClosing}}"></select>
    </th>
    <th>
        <input type="checkbox" ng-model="{{field.checkMorning}}" />
    </th>
    <th>
        <input type="checkbox" ng-model="{{field.checkEvening}}" />                                        
    </th>
</tr>
</thead>
</table>
<!-- add extra field -->
<button class="btn" ng-click="addNew()"c>add extra field</button>
<!-- delete last field -->
<button ng-show="fields.length > 0" class="btn" ng-click="deleteLast()"c>remove last extra field</button>

和这里的angular/javascript:

$scope.fields = [];
$scope.addNew = function() {
    var newItemNo = $scope.fields.length+1;
    $scope.fields.push(
                        {
                            'day'            :'day'+newItemNo,
                            'month'          : 'month'+newItemNo,
                            'morning'        : 'morning'+newItemNo,
                            'eveningOpen'    : 'eveningOpen'+newItemNo,
                            'eveningClosing' : 'eveningClosing'+newItemNo,
                            'checkMorning'   : 'checkMorning'+newItemNo,
                            'checkEvening'   : 'checkEvening'+newItemNo
                        }
                      );
    console.log($scope.fields);
};
$scope.deleteLast = function() {
    $scope.fields.pop();
}

我是否错过了一些限制,因为每个在堆栈上这样做的人都成功了:/

您的问题是ng-model="{{ obj。prop }}",应该是ng-model="obj.prop"。使用{{}}会让Angular尝试绑定对象的resolved属性。此外,由于您的对象不是唯一的,我建议将track by function添加到迭代中。

Edit:另外,下面提到的select也需要ngOptions指令。复选框可以通过ngTrueValue和ngfalse指令使用字符串值。

正如已经说过的,您不应该绑定ng-model="{{field.day}}",只使用ng-model = "field.day"

但是另一个问题是,您绑定到没有任何选项的select元素。

<select ng-model="field.day">
  <!--<option val="1">Need some options here</option> -->
</select>

你想要的下拉选项是什么?如果您将select更改为input,您将看到该值正在被绑定。

<input type="text" ng-model="field.day"></input>

同样,对于复选框,您应该绑定到一个布尔值。如果绑定到字符串值,如checkEvening1,则复选框将始终未选中。

JSFiddle