在Angular中继器中使用动态阵列上的拼接

时间:2015-03-30 10:06:59

标签: javascript arrays angularjs

尝试使用splice从数组中删除对象时遇到问题。我有一个通过UI动态创建的数组,并存储在名为$ scope.productAttributes.Products的范围变量中。这是它的样子......

[
{
    "ProductLabel":"Net",
    "Code":"ela",
    "Site":"SITE1"
},
{
    "ProductLabel":"Link",
    "Code":"eli",
    "Site":"SITE1"
},
{
    "ProductLabel":"24-port managed PoE switch",
    "Code":"24p",
    "Site":"SITE2"
},
{
    "ProductLabel":"Dedicated Firewall",
    "Code":"ded",
    "Site":"SITE2"
},
{
    "ProductLabel":"Link",
    "Code":"eli",
    "Site":"SITE3"
},
{
    "ProductLabel":"IPv4 Addresses",
    "Code":"ip4",
    "Site":"SITE3"
}
]

然后我在角度转发器中显示该数组并将其按“站点”分组(这可能是问题的一部分)......

<div ng-repeat="(key, value) in productAttributes.Products | groupBy: 'Site'">
    <strong>{{key}}</strong>
    <div ng-repeat="site in value">
        <h4>{{site.ProductLabel}}</h4>
        <sapn href="" ng-click="deleteItem($index)" class="text-danger">Remove {{site.ProductLabel}}</span>
    </div>
</div>
</div>

在删除按钮上,我传入对象的索引并使用拼接功能...

 $scope.deleteItem = function (index) {
        $scope.productAttributes.Products.splice(index, 1);
};

所以问题是$ index总是为零(我注意到这是来自console.log),因为我提到我认为它可能归结为groupBy,但我不确定。有谁知道什么出错了?感谢

更新

看起来问题在于嵌套转发器中的$ index。所以如果结构上方的json是......

第1站:

产品:净 - $指数:0

产品:链接 - $ index:1

第2站:

产品:24端口 - $ index:0

产品:Dedicated - $ index:1

第3站:

产品:链接 - $ index:0

产品:IPV4 - $ index:1

因此,如果我尝试删除SITE3中的IPV4产品,它会删除Site1中的LINK产品,因为它具有相同的$ index。我有什么想法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

我们不能依赖$ index,因为从数组中删除项目后它不包含更新的值。

从UI动态传递对象,并使用以下代码将其从模型中删除:

在Html中:

<div ng-repeat="(key, value) in productAttributes.Products | groupBy: 'Site'">
    <strong>{{key}}</strong>
    <div ng-repeat="site in value">
        <h4>{{site.ProductLabel}}</h4>
        <sapn href="" ng-click="deleteItem(site)" class="text-danger">Remove {{site.ProductLabel}}</span>
    </div>
</div>
</div>

在JavaScript中:

$scope.productAttributes.Products.splice
    ($scope.productAttributes.Products.indexOf(site), 1);

这会导致模型使用repeater中的更新值进行更新,并在UI上重新呈现它。

答案 1 :(得分:2)

好的 - 我最终这样做了,似乎有效了

$scope.deleteItem = function (item) {
        var index = $scope.productAttributes.Products.indexOf(item);
        $scope.productAttributes.Products.splice(index, 1);
    };

所以传递整个对象似乎已经奏效了。我不确定为什么。