0

I have implemented AngularJS inside of the RoR framework. I am trying to create a multi-filter for the "ng-repeat" method to filter the JSON data by "month_id" and "year_id".

Currently I have the following code:

JSON:

[
  {  "date":"October 4, 2015",
     "month_id":"10",
     "year_id":"2015",
     "name":"Chris",
     "title":"Painter",
     "company":"Freelancer",
     "description":"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" },

    { "date":"October 3, 2015",
      "month_id":"10",
      "year_id":"2015",
      "name":"Rebecca",
      "title":"Writer",
      "company":"John H. Hickenloop",
      "description":"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" },

    { "date":"October 22, 2014",
      "month_id":"10",
      "year_id":"2014",
      "name":"Josh",
      "title":"Riddler",
      "company":"Florida Museum",
      "description":"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." }
]

Controller:

var myApp = angular.module('myApp', []);

myApp.controller("MyController", function MyController($scope, $http){
    $http.get("/assets/data.json").success(function(data){
    $scope.artists = data;

      String.prototype.trunc = String.prototype.trunc ||
      function(n){
      // this will return a substring and
      // if its larger than 'n' then truncate and append '...' to the string and return it.
      // if its less than 'n' then return the 'string'
      return this.length>n ? this.substr(0,n-1)+'...' : this;
    };
    $scope.myFilter = function(){
      var currentDate = new Date;
      return year_id === currentDate.getFullYear() && month_id === (currentDate.getMonth() + 1);
      };
    });
  });

HTML:

<div ng-controller="MyController">
  <ul>
   <li ng-repeat="item in artists | filter: myFilter">
     <h1>{{item.date}}</h1>
     <p>{{ item.description.trunc(100) }}</p>
   </li>
  </ul>
</div>
3
  • your filter needs to take array as input and return filtered array. . What is year_id and month_id in your function? Also not sure why you put the String.prototype in an ajax callback. Really is a global thing unrelated to angular or ajax Commented Oct 5, 2015 at 16:08
  • "year_id" and "month_id" are from my JSON file. I'm guessing I am not targeting them correctly? I would like to check whether they are in their current month/year, and if so, have "ng-repeat" filter the data and output the description and date with matching month/year. Could you provide an example solution for what you mean? Commented Oct 5, 2015 at 16:45
  • 1
    use angular $filter or Array.prototype.filter() Commented Oct 5, 2015 at 16:49

1 Answer 1

2

Your main issue is that you're comparing numbers to strings and using the strong comparison operator (remember, '2' !== 2). Try using the .toString() method in your filter function on currentDate.getFullYear() and currentDate.getMonth(). Or you could use the weak comparison operator, ==.

'2' == 2;  // true
'2' === 2; // false

The Angular way of doing this would be to write your own filter and keep that logic outside of your controller and, in so doing, make that function reusable everywhere in your app. You can find documentation for writing custom filters at https://docs.angularjs.org/guide/filter. I would approach this like so:

myApp
.controller('MyController', function MyController($scope, $http) {
    /** YOUR CODE HERE */
})
.filter('thisMonth', [function() {
    return function(array) {
        var results = [],
            today   = new Date(),
            month   = (today.getMonth() + 1).toString(),
            year    = today.getFullYear().toString();

        angular.forEach(array, function(item, index) {
           if (item.month_id === month && item.year_id === year) {
               this.push(item);
           } 
        }, results);

        return results;
    };
}]);

Then in your ng-repeat, you could just use:

<ul>
    <li ng-repeat="item in items|thisMonth">item.date</li>
</ul>

Or, in your controller, you could use

$scope.sortedItems = $filter('thisMonth')($scope.items);

EDIT: Using that last approach, you would need to include $filter as a dependency.

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

8 Comments

That did not fix the issue for me :/
Which approach didn't work? Using .toString or the custom filter?
Can you create a plknr to show how you did this? I've tested this using your code from above and it's accomplishing what you had described above.
So you don't include custom filters inside controllers, but rather alongside controllers. See my new edit.
Last comment, see forked plunk: plnkr.co/edit/C2LmUVfshTffCIvDH0pY (updated markup and JS).
|

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.