2

I'm learning Angularjs and I have a small question:

I have the following array returned from user

userPreferences = [7,5,4]

I have an object that I'm using ng-repeat to display all news and looks like this:

{
    "id": 1,
    "preferences": [
      3,
      4
    ]
}

So, I want to use in my ng-repeat, the array returned from user preferences, and sort the news displaying the preferences first, then below the other news, is that possible?

Something like:

<li ng-repeat="new in news | filter:{'userPreferences' : new.preferences}">

I don't really know if I have to use filter, orderBy or sort, any help please?

5
  • So if new.preferences array has all the elements of userPreferences, you want to show them is it? Commented Jun 7, 2016 at 5:18
  • Yes, but like, new.preferences has category 3 and 4, and userPreferences has 3, this new will be displayed first and all the others below it. like, sorting by relevance i think Commented Jun 7, 2016 at 5:20
  • You want to display all the new's too which don't match the user preference? Commented Jun 7, 2016 at 5:23
  • Yeah, bellow the ones that matchs, i just don't know if that's possible and how to achieve this. Commented Jun 7, 2016 at 5:25
  • In above sample object ,news.preferences is 3,4,show how you going to display it,Where this id belongs? Commented Jun 7, 2016 at 5:59

1 Answer 1

1

You can have your own function that returns the number of the matched preferences on your scope:

function intersect(array1, array2) {
    return $filter('filter')(array1, function(n){
    return array2.indexOf(n) != -1;
  });
}

$scope.matchedPreferences = function(n) {
    return intersect(n.preferences, $scope.userPreferences).length;
};

and pass it to orderBy filter:

<li ng-repeat="n in news | orderBy:matchedPreferences:true">{{n}}</li>

This will order the news by the number of matched preferences in the descending order.

Here the Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.