Angular - 完全从数组中删除对象

时间:2017-08-21 06:29:57

标签: javascript angularjs arrays

我有一个这样的数组:

Array[3]
0:Object
  ID:7
  name:"bestRes3t"
  profile:"rest7.png"
  rate:0
  restaurantCitySlug:"NY"
  slug:"fo4o"
  __proto__:Object
1:Object
  ID:3
  name:"bestRest"
  profile:"rest.png"
  rate:1
  restaurantCitySlug:"NY"
  slug:"foo"
  __proto__:Object
2:Object
  ID:7
  name:"bestR242es3t"
  profile:"re3st7.png"
  rate:2
  restaurantCitySlug:"NY"
  slug:"fo244o"
  __proto__:Object

我决定从我的数组中删除单个对象(ID = 3)。我尝试过删除myArray[1],但它没有改变我的数组的长度。由于ng-repeat取决于阵列的长度,因此它成为一个大问题。

<li ng-repeat="(resNo,restaurant) in myArray" style="margin-bottom: 20px"
                dnd-draggable="restaurant"

                dnd-effect-allowed="move"
                dnd-moved="myArray.splice($index, 1)"
                dnd-selected="myArray.selected = resNo"
                dnd-callback="myArray.length"
                >

它显示了三个列表项,其中一个是空的但是我想显示其中几个因为我已经删除了其中一个。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

试试这样的事情:

    app.controller('demoController', function($scope) {
    // initial items
    $scope.items = [
        'item one',
        'item two',
        'item three'
    ];

    // remove an item
    $scope.remove = function(index) {
        $scope.items.splice(index, 1);
    };
});

HTML:

<div ng-controller="demoController">
<!-- list of items with a button to remove that item -->
<ul>
    <li ng-repeat="item in items">
         <button ng-click="remove($index)">Remove</button>
    </li>
</ul>
</div>

看看这个简单的例子here