-->

ng-change does not work in the table row generated

2019-08-11 02:48发布

问题:

I have a simple table row.

The row is generated by below code.

<tr ng-init="cacheChanged">
    <td>Expiration Period</td>
    <td ng-repeat="system in tableData.regions[0].systems">
        <input type="text" ng-model="system.cacheDuration" ng-change="cacheChanged=true">
        <span>h</span>
    </td>
    <td>
        <button type="button" ng-click="saveCache()" ng-disabled="!cacheChanged">Save</button>
    </td>
</tr>

When any of the four values changed, the save button is supposed to be enabled. However, it is still disabled all the time. Anyone knows why? Thanks in advance!

回答1:

In your case you should use $parent.cacheChanged instead of cacheChanged variable. As ng-repeat does create child scope for each loop while rendering DOM. In short the cacheChanged variable inside ng-repeat is not same as that of cacheChanged used there on button.

Markup

<td ng-repeat="system in tableData.regions[0].systems">
    <input type="text" ng-model="system.cacheDuration" ng-change="$parent.cacheChanged=true">
    <span>h</span>
</td>

There is better way to go for it will be using Dot rule while defining ng-model, look at this detailed answer here.