using ng-model within nested ng-repeat directives

不问归期 提交于 2019-11-30 17:18:01
Ben Lesh

This is a common issue for people in Angular. What's happening is ng-repeat creates it's own scope, and if you pass an array of value types into it (such as an array of booleans), updating them will not update the parent scope. You need to pass an array of reference types to the ng-repeat and update those in order for it to persist:

Here is a solution showing this based off of your fiddle

machine.noteMatrix = [
    [
        { value: false },
        { value: false }, 
        { value: false }
    ],
    [
        { value: false },
        { value: true }, 
        { value: false }
    ],
    [
        { value: false },
        { value: false }, 
        { value: false }
    ]
];

It's ugly, I know, but the alternative is uglier. You'd need to do something to manage your own loop and reference the values via the $parent or $parent.$parent object. I don't recommend this.

Your first solution seems to be correct.

This appears to be a bug, introduced in the unstable branch of angularJS (you are using 1.1.4, which is unstable - the stable version, 1.0.6, works as expected)

EDIT:

Turns out this isn't a bug, but a new feature - the ngRepeat directive now allows for a tracking function to be defined (associating the model's id with the DOM element), and no longer allows for these tracking variables to be repeated. See the corresponding commit, the docs for 1.1.4 on ngRepeat and the changelog

You don't need to alter your model or access the $parent. What's missing is "track by $index":

    <tr ng-repeat="track in machine.noteMatrix">
        <td>--</td>                
        <td ng-repeat="step in track track by $index">                    
            <input type="checkbox" ng-model="track[$index]"> {{step}}
        </td>
    </tr>

Here it is in yr fiddle.

More information: Angular ng-repeat dupes

I'm not sure if track by existed yet when the question was asked, so the other answers may have been correct at the time, but in current Angular this is the way to go.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!