如何在angular.forEach内部动态添加ng-model

时间:2018-12-19 09:21:22

标签: angularjs

这是我在加载时附加到我的模态中的内容,除了复选框行之外,它工作正常。

//$scope.items is retrieved by an api, and looks something like this.
 $scope.items[0] = ['delivered' : true, 'status': 'delivered']
 $scope.items[1] = ['delivered': false, 'status': 'pending']

angular.element('.row-modal').empty();
request.success(function(response) {
    $scope.paymentTransactionServices = response;

    angular.forEach($scope.paymentTransactionServices, function(value, index) {
        var deliveredBy = value.deliveredBy ? value.deliveredBy.email : null;
        angular.element('#table-services').append('<tr class = "row-modal">' +
            '<td>' + value.title + '</td>' +
            '<td>' + deliveredBy + '</td>' +
            '<td>' + '<label class="checkbox-inline">' +
            ' <input type="checkbox" ng-model=' + $scope.paymentTransactionServices[index].delivered + ' ng-change="print()" />' + value.status + '</label> </td>' +
            '<td>' + value.delivery_date + '</td>' +
            '</tr>'
        );
    })

我期望的是,如果“已交付”为false,则不应选中该复选框,如果为true,则应选中它。在单击时,我想触发一个函数,但是它不起作用...

2 个答案:

答案 0 :(得分:2)

You should never alter the dom like that, as this may result in unexpected errors and memory leaks in you application.

You should always use directives & components for this kind of stuff.

What you should do, in your template, is:

<table id="table-services">
    <tr>
        <th>Title</th>
        <th>Delivered by</th>
        <th>Status</th>
        <th>Delivery date</th>
    </tr>
    <tr ng-repeat="service in paymentTransactionServices" class="row-modal">
        <td>{{ service.title }}</td>
        <td>{{ service.deliveredBy.email || null }}</td>
        <td>
          <label class="checkbox-inline">
            <input type="checkbox" ng-model="service.delivered" ng-change="print()" />
            {{ service.status }}
          </label>
        </td>
        <td>{{ service.delivery_date | date }}</td>
    </tr>
</table>

答案 1 :(得分:-2)

如果需要选中一个复选框,则必须在HTML元素中添加 checked 属性。在上述情况下,该元素上没有选中的属性。

另一方面,我怀疑复选框是否存在单击事件。请改用更改

检查以下内容是否有效

input type="checkbox" checked={{value.delivered}} (change)=print()