从过滤的ng-repeat中删除元素后更新选定的数组元素

时间:2015-05-15 04:23:23

标签: angularjs angularjs-ng-repeat angularjs-filter

我有一个用户列表,您单击某个用户来选择它,并在选中时将该元素放入对象$ scope.selectedMember中。我使用ng-repeat和搜索框过滤器。重要的是$ scope.selectedMember应始终使用成员填充。

问题在于我试图克服:   - 将最后一个用户拼接出来需要自动选择已过滤数组中的最后一个用户,即使它已经通过搜索过滤了一些成员。

HTML

<div ng-app="myApp" ng-controller="MainCtrl">
    <input ng-model="search"></input>
    <div ng-repeat="(key, member) in members | filter:search | orderBy :'-name'">
        <li ng-class="{active: retActive(key)}"
            ng-click="selectThis($index)">
            name: {{member.name}} key: {{key}}
                <button ng-click="deleteThis(key)">delete</button>
        </li>
    </div>
    Selected member name: {{selectedMember.name}}
</div>

JS

angular.module('myApp', []);

function MainCtrl($scope) {

    $scope.members = [
                          {"name":"a", "viewIndex":0},
                          {"name":"b", "viewIndex":1},
                          {"name":"bb", "viewIndex":2},
                          {"name":"bb", "viewIndex":3},
                          {"name":"c", "viewIndex":4},
                          {"name":"d", "viewIndex":5},
                          {"name":"e", "viewIndex":6}
                         ];

    $scope.activeIndex = 0;
    $scope.selectedMember = $scope.members[0];

    $scope.selectThis = function (index) {
        $scope.activeIndex = index;
        //put array member into new object
        $scope.selectedMember = $scope.members[index];  
    }

    //splice the selected member from the array  
    $scope.deleteThis = function (index) {
        $scope.members.splice(index, 1);
        $scope.selectThis(index);  
    }

    //angular copy and push member to the array
    $scope.duplicateThis = function (index) {

    }

    // change class if member is active
    $scope.retActive = function (index) {
        return $scope.activeIndex == index;
    }
}

CSS

.active {
    color:blue;
}

Link to JSFiddle

1 个答案:

答案 0 :(得分:0)

我看到的一个问题是你将$ index传递给selectThis($ index)。当你过滤数据时,循环的$ index不再代表数组中项目的实际索引 - 所以你应该传递selectThis一个键,而不是$ index。