我正在使用AngularJS过滤器来挑选电影,并且一直在寻找使用多个搜索词。如果影片尚未被过滤器捕获,则它将转到数组的顶部。最终我想通过点击来排序数组,但同时我只想设置它,这样,如果电影已经在搜索结果数组中,它将被移动到数组的顶部以便首先看到。任何帮助将不胜感激!
// New module:
var app = angular.module('movieFinder', []);
// Search function:
app.filter('searchFor', function() {
return function(arr, searchString) {
// Show all movies until search begins
if(!searchString) {
return arr;
}
var result = [];
// Search for each word. Change to lowercase. Remove any punctuation. Split into array.
searchArray = searchString.toLowerCase().replace(/[^\w\s]|_/g, "").split(" ");
// Work through each word.
for (i = 0; i < searchArray.length; i++) {
// Work through each movie.
angular.forEach(arr, function(movie) {
if((movie.title.toLowerCase().indexOf(searchArray[i]) !== -1) ||
(movie.description.toLowerCase().indexOf(searchArray[i]) !== -1) ||
(movie.director.toLowerCase().indexOf(searchArray[i]) !== -1) ||
(movie.country.toLowerCase().indexOf(searchArray[i]) !== -1) ||
(movie.year.toString().indexOf(searchArray[i]) !== -1) ||
(movie.genre.toLowerCase().indexOf(searchArray[i]) !== -1) ||
(movie.keywords.toLowerCase().indexOf(searchArray[i]) !== -1)) {
// If the movie is not listed...
if (result.indexOf(movie) === -1) {
// Insert at top of array
result.unshift(movie);
};
};
});
}
return result;
}
});
// The controller
function MovieFinderController($scope){
// The data model
$scope.movies = [
{
title: 'The Beat That My Heart Skipped',
description: 'Will Thomas still lead a life of crime and cruelty, just like his thuggish father, or will he pursue his dream of becoming a pianist?',
director: 'Jacques Audiard',
country: 'France',
year: 2005,
genre: 'Noir Thriller',
cover: 'images/thebeatthatmyheartskipped.jpg',
keywords: 'piano, gangster, broody, thug'
},{
title: 'Chungking Express',
description: 'Two melancholy Hong Kong policemen fall in love: one with a mysterious female underworld figure, the other with a beautiful and ethereal server at a late-night restaurant he frequents.',
director: 'Wong Kar Wai',
country: 'Hong Kong',
year: 1994,
genre: 'Romantic Comedy',
cover: 'images/chungkingexpress.jpg',
keywords: 'fast food, cops, music, wigs, dancing, Chinese food, heartache, eating'
}
(...)
感谢您的帮助!
答案 0 :(得分:1)
使用Array.prototype.unshift
在数组的开头附加内容。
Array.prototype.unshift.apply(<your array>, <movies to be added at beginning>);