Search code examples
javascriptangularjsarraysionic-frameworkangular-ngmodel

Create a favorite list in AngularJS


I want to create a favorite list in my application based on user selection. In my app, I use a long JSON file with a bunch of text which is loaded with $http.get(). This is code for displaying content in my view.

<ion-view>
<ion-nav-title></ion-nav-title>
<ion-content>
    <div class="card" ng-repeat="list in items | filter: { id: whichid }">
        <div class="item item-text-wrap"
             ng-repeat="item in list.content | filter: { id2: whichid2 }"
             ng-bind-html="item.description.join('')">
            <h3>{{ item.name }}</h3>
            <p>{{ item.description }}</p>
        </div>
    </div>
</ion-content>

The basic idea for creating a favorite list is to save displayed text in the array. After that, I can easily print that array in a template for the favorite list.

So the problem is how I can save text/data form expression ({{ item.name }}, {{ item.description }}) to the array? Or if anyone has some other idea for making that favorite list.


Solution

  • Pass the item details to a function defined in your controller using ng-click and push it into an array as shown below :

    <ion-view>
    <ion-nav-title></ion-nav-title>
    <ion-content>
        <div class="card" ng-repeat="list in items | filter: { id: whichid }">
            <div class="item item-text-wrap" ng-click="favouriteThis(item)"
                 ng-repeat="item in list.content | filter: { id2: whichid2 }"
                 ng-bind-html="item.description.join('')">
                <h3>{{ item.name }}</h3>
                <p>{{ item.description }}</p>
            </div>
        </div>
    </ion-content>
    

    In your controller : Write the "favouriteThis" function to push the favourited item every time the user clicks on it :

    $scope.favouriteList = [];
    $scope.favouriteThis = function (item) {
     $scope.favouriteList.push(item); // make sure to check for duplicates before pushing the item, the logic for which i've not included here. 
    }
    

    As you have all the favourited item details in the "$scope.favouriteList", you can use that information in your favourite list directly. To make it more accurate, while checking for duplicates you can also record the number of times user interacted with a particular item using which you can show the most interacted item on the top of the list. Hope this helps :)