在过滤搜索角度js后保持li被选中

时间:2017-05-31 23:19:18

标签: jquery css angularjs

我在ul中有三个列表项。有三个名字:罗伊,萨姆,大卫。我可以点击每个li点击就好了。但是,当我进行搜索并返回时,所选项目不再突出显示。关于如何让他们被选中的任何建议。这是我的小提琴:



var app = angular.module("ap",[]);

app.controller("con",function($scope){
		$scope.firstNames = ['Sam', 'David', 'Roy'];

});

app.directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.toggleClass(attrs.toggleClass);
            });
        }
    };
});

.active {
  background-color:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<input type="text" ng-model="searchText"/>
<ul ng-repeat="firstName in firstNames | filter:searchText">
<li toggle-class="active">{{firstName}}</li>

</ul>
  
</body>
&#13;
&#13;
&#13;

http://jsfiddle.net/baa2G/126/

感谢。

2 个答案:

答案 0 :(得分:1)

编辑,因为我没有正确地阅读你的问题!

使用Angular将您的选择存储在控制器中。

我已将firstNames修改为users并将每个条目更改为对象。

$scope.users = [
    {name: 'Sam', isSelected, false},
    {name: 'David', isSelected, false}, 
    {name: 'Roy', isSelected, false}
];
$scope.toggleSelection(user){
    user.isSelected = !user.isSelected;
}
<ul ng-repeat="user in users | filter:searchText">
<li ng-click="toggleSelection(user)" ng-class="{'active': user. isSelected}">{{user.name}}</li>

答案 1 :(得分:1)

请改用ng-class。始终考虑如何首先使用您的数据模型...并让它控制视图

<li ng-class="{active: selected[firstName]}" 
    ng-click="toggleSelected(firstName)">{{firstName}}</li>

控制器:

   $scope.selected = selected = {};
   $scope.toggleSelected = function(name){  
      selected[name] = !selected[name];
   }

<强> Demo