Data binding 角度:如何使用ng repeat绑定到整个对象

Data binding 角度:如何使用ng repeat绑定到整个对象,data-binding,angularjs,radio-button,angularjs-ng-repeat,Data Binding,Angularjs,Radio Button,Angularjs Ng Repeat,我刚刚开始在Angular中进行实验,对于如何最好地使用ng repeat进行绑定感到困惑。我基本上理解了创建子范围的要点。我的问题更基本:)对于html,如下所示: <div ng-controller="swatchCtrl" class="swatch-panel"> Swatches <ul> <li ng-repeat="swatch in swatchArray" class="swatch">

我刚刚开始在Angular中进行实验,对于如何最好地使用ng repeat进行绑定感到困惑。我基本上理解了创建子范围的要点。我的问题更基本:)对于html,如下所示:

<div ng-controller="swatchCtrl" class="swatch-panel">
    Swatches
    <ul>
        <li ng-repeat="swatch in swatchArray" class="swatch">
            <input
                type="radio"
                name="swatches"
                ng-model="$parent.currentSwatch"
                value="{{swatch}}"              
            >
            <label class="swatch-label">
                <div class="swatch-color" style="background-color: #{{swatch.hexvalue}};"></div
                ><span class="swatch-name">{{swatch.colorName}}</span> 
            </label>
        </li>
    </ul>

    currentSwatch is:
    <pre>{{currentSwatch | json}}</pre>

    currentSwatchObj is:
    <pre>{{currentSwatchObj | json}}</pre>
        how do I tell this to fire??

    swatchArray is:
    <pre>{{swatchArray | json}}</pre>
</div>

我想:

a) 当用户单击单选按钮时,我希望它设置currentSwatch对象的colorName和hexvalue属性。现在绑定似乎给了我一个数组中的字符串化对象。如何观察currentSwatch的返回,以便将其解析回可用对象?简单,我知道,但我错过了什么

b) 当用户单击单选按钮时,我想我希望将原始数组中对应的“selected”键的值设置为“true”。反之亦然。假设在调色板中一次只能选择一个样例。(理论上,我希望以后能够遍历数组,假设不同的键和值有时可能不是唯一的。)

这类东西对于jquery方法来说非常简单,但我想学习惯用的方法。提前感谢您的帮助。

我不会监听ng click事件,而是将所选元素的索引设置为一个名为“currentSwatchIndex”的变量

仅知道currentSwatchIndex就足以识别选定的swatchObject。因此,您可能可以删除当前SwatchOBJ和swatchArray的选定属性。
您始终可以通过数组访问以编程方式获取所选样例。

对于将来可以在选择中访问此样例的用户,您不需要使用任何索引,选择操作必须如下所示:

是什么让您认为
currentSwatch
是字符串表示?您在标记中看到字符串的唯一原因是您使用的是
json
过滤器,它只是将其转换为json,然后再将其显示在屏幕上<控制器中的code>currentSwatch实际上是一个对象。如果您删除
| json
,那么您将看到它在不逃避任何约束的情况下将对象放出来,您当然是对的……谢谢,这很简单和优雅。我担心的是,在导入样例库或在swatchArray上执行排序/过滤操作时,仅仅使用swatchIndex可能会变得棘手,这是我在自己的小教程中想象的。避免ng点击事件有什么实际好处,还是只是风格问题?(我想我也更喜欢在数组中保留“selected”属性,作为使用css设置活动样例样式的一种方式。)谢谢,这正是我昨天和今天学习Angular时一直在挠头的地方。我很高兴这有帮助:)
function swatchCtrl($scope) {
    $scope.swatchArray = [
        {colorName:'Red', hexvalue: 'ff0000', selected: 'false'},
        {colorName:'Green', hexvalue: '00ff00', selected: 'false'},
        {colorName:'Blue', hexvalue: '0000ff', selected: 'false'}
    ];

    $scope.currentSwatch = {};
}
<li ng-repeat="swatch in swatchArray" class="swatch">
    <input
        type="radio"
        ng-model="$parent.currentSwatchIndex"
        value="{{$index}}"              
    >
</li>
$scope.$watch('currentSwatchIndex', function(newValue, oldValue) {
    $scope.currentSwatchObj = $scope.swatchArray[newValue];
    $scope.swatchArray[newValue].selected = true;
    $scope.swatchArray[oldValue].selected = false;
});