我有一个由ng-repeat指令解析的列表。该列表可由用户过滤。这部分工作正常。
过滤后的列表的第一项会在页面的其他位置突出显示。
我遇到以下问题:
当用户点击列表中的某个项目时,突出显示的项目应该被单击的项目替换,直到完成另一个过滤。
JSFiddle链接here
function MyCtrl($scope) {
$scope.list = [{
id: 'a 1'
}, {
id: 'a 2'
}, {
id: 'b 3'
}];
$scope.itemFocus = function (item) {
//we don't want to create a duplicate in a repeater
//$scope.filteredItems[0] = item;
};
}
<div>
<input type="text" ng-model="searchItems" />
<p ng-if="filteredItems[0]">{{filteredItems[0].id}}</p>
</div>
<!-- some code -->
<ul>
<li ng-repeat="item in filteredItems = (list | filter:searchItems)"
ng-click="itemFocus(item)">{{item.id}}</li>
</ul>
答案 0 :(得分:1)
请参见此处:http://jsfiddle.net/jk37o92d/
JS:
function MyCtrl($scope) {
$scope.list = [{
id: 'a 1'
}, {
id: 'a 2'
}, {
id: 'b 3'
}, {
id: 'b 4'
}];
$scope.$watch('searchItems', function () {
$scope.selected = 0;
});
$scope.selected = 0;
$scope.itemFocus = function (item) {
$scope.selected = item;
};
}
HTML:
<div ng-app>
<div ng-controller="MyCtrl">
<div>
<input type="text" ng-model="searchItems" />
<p ng-if="filteredItems[selected]">{{filteredItems[selected].id}}</p>
</div>
<!-- some code -->
<ul>
<li ng-repeat="item in filteredItems = (list | filter:searchItems)" ng-click="itemFocus($index)">{{item.id}}</li>
</ul>
</div>
</div>
答案 1 :(得分:0)
我不确定我理解你想要什么,但也许这样的事情会有所帮助
function MyCtrl($scope) {
$scope.list = [{
id: 'a 1'
}, {
id: 'a 2'
}, {
id: 'b 3'
}];
//just initiating value, could also be set by ng-init in your html
$scope.focused = $scope.list[0];
$scope.itemFocus = function (item) {
$scope.focused = item;
};
}
然后
<div ng-app>
<div ng-controller="MyCtrl">
<div>
<input type="text" ng-model="searchItems" />
<p ng-model="focused">{{focused.id}}</p>
</div>
<!-- some code -->
<ul>
<li ng-repeat="item in filteredItems = (list | filter:searchItems)" ng-click="itemFocus(item)">{{item.id}}</li>
</ul>
</div>
</div>