What is the correct method for using $filter with a promise object in a controller?

I was working on implementing pagination with this forked code plunker and everything was running smoothly. However, when I attempted to modify the code to fetch data from a Json file, it stopped functioning properly.
To see the code in action, please comment out lines: [13, 14, 15], and uncomment lines: [16 -> 37].
The issue seems to be related to the $filter function returning undefined when fetching data from a Json file. This leads me to believe that because the object is now a promise, it might be causing the $filter function to break, although I'm not entirely certain.
The error occurs within these two functions (when making the Json call):

$scope.search = function () {
  $scope.filteredItems = $filter('filter')($scope.items, function (item) {
    for(var attr in item) {
      if (searchMatch(item[attr], $scope.query)){
        return true;
      }
    }
    return false;
  });
  // take care of the sorting order
  if ($scope.sortingOrder !== '') {
    $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sortingOrder, $scope.reverse);
  }
  $scope.currentPage = 0;
  // now group by pages
  $scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
  $scope.pagedItems = [];
  for (var i = 0; i < $scope.filteredItems.length; i++) {
    if (i % $scope.itemsPerPage === 0) {
      $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
    } else {
      $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
    }
  }
};

Error Message:

TypeError: Cannot read property 'length' of undefined
          at Object.$scope.groupToPages (controllers.js:66:45)
          at Object.$scope.search (controllers.js:61:12)
          at new controllers.MainCtrl (controllers.js:99:10)

I would greatly appreciate any assistance. Thank you in advance.

Answer №1

The issue arose because the filter was being executed before the promise returned from $http had resolved, leading to the items object being undefined.
The resolution can be found in a discussion on Google groups post ( proper way to call $filter in the controller? ).
To address this, the following steps were taken:

Items.then(function(data) {
    $scope.items = data;
    //invoke $scope.search here, instead of at line 100
    $scope.search();
});

As a result, the plunker now functions correctly. Special thanks to Florian Orben from the google AngularJS group.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery will not carry out the initial trigger action more than once

I've successfully implemented a feature where clicking on one of the 3 divs causes the main container to slide half away by 600px and reveal a new container with additional options. However, I'm facing an issue where after closing the new content ...

The transfer of JSON information from View to Controller yields no value

My goal is to create functionality where users can add and delete JQuery tabs with specific model data, and then save this data to a database. I'm attempting to use an ajax call to send JSON data to the controller, but I am encountering an issue where ...

Having trouble retrieving the data from a post request in Express

I'm encountering an issue while attempting to access the data in a POST request. Even after using console.log(req.body), I only receive an empty {}. My suspicion is that the error may lie somewhere within the markup? Below is the relevant client-sid ...

Incorporating exotic elements into d3.js, currently visible

I am attempting to insert checkboxes and text within a node. Refer to the image below for my desired outcome. https://i.sstatic.net/YhrvZ.png While I can see the checkbox in the elements view, it is not visible on the page itself. https://i.sstatic.net/ ...

Mastering various mathematical operations in Vue.js

I am attempting to calculate the percentage of a value and then add it back to the original value using Vue.js. Here is an example: 5 / 100 * 900 + 900 = 945.00 (standard calculation) 5 / 100 * 900 + 900 = 90045 (Vue.js calculation) This is the code I ha ...

Merge arrays with identical names within the same object into one cohesive object containing all elements

I just started using Vue and I'm not entirely sure if it's possible to achieve what I have in mind. Here is the structure I have: { "items":[ { "total":1287, "currency":"USD", "name":"string", "itemID":"", "pro ...

Error: The function passport.use is undefined

I've been trying to integrate the passport service into my app, but I keep encountering this error. Despite installing all the required dependencies, I can't seem to resolve it. I hope someone here can offer some guidance: Here is the error mess ...

Creating a collection of arrays that are named based on the properties of an object

After calling an ajax service, I received a collection of objects where Object (A) properties are Group, order, salary. For example, the objects could be [Employee, 1, 1500],[Management, 2, 2000], [Employee, 3, salary]. My task is to create an array for e ...

What is the cost associated with monitoring events across the entire document?

Exploring the option of event delegation for multiple buttons spread across a HTML page. Considering listening to the entire document for click events as opposed to having individual listeners on each button. Is it worth the potential cost with over 100 ...

Using a per-field Javascript function for a dropdown

Seeking advice on how to effectively address this issue. I have 3 different prices and when a user selects "yes" from the dropdown, I want to reveal a hidden field. Please refer to the example below: http://jsfiddle.net/adder1999/BsMkj/ <div> ...

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

Adding an onload event to a popup window using Javascript

I am attempting to add an onload event to a popup window in the following way: var newPopup = window.open(PARAMS...); newPopup.onload = function() {window.opener.unlockObj(id);} The goal is to disable the button that launches the popup window until all o ...

npm update fails to update specific packages

After React was updated to version 0.15 to address the issue of excessive generation of tags, I made the decision to update my project.</p> <p>However, when I ran the command <code>npm update, it only updated to version 0.14.8. Running ...

Using jQuery to retrieve the TD value

I'm attempting to retrieve the TD value using the Value attribute.... Let's say I have the following HTML markup: <td nowrap="nowrap" value="FO2180TL" class="colPadding" id="salesOrderNumber1">bla bla </td> So, I tried this- v ...

"Encountering issue with binding ng-repeat to object name, not

I'm currently facing an issue where I am attempting to bind the ng-repeat object name that is being passed from a parent repeat (refer to "dType.name"), but unfortunately, the name is not binding. I have experimented with two different methods: (only ...

The expiration time and date for Express Session are being inaccurately configured

I'm experiencing an issue with my express session configuration. I have set the maxAge to be 1 hour from the current time. app.use( session({ secret: 'ASecretValue', saveUninitialized: false, resave: false, cookie: { secure ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

Reposition checkbox within dropdown list

To create a dropdown menu with textboxes, I implemented the code found in this Stack Overflow answer: Now, I am looking to reposition the dropdown menu to align with a specific piece of text, preferably to the right side of the 'Textpiece'. I at ...

How can Cognito be integrated on a pure HTML & JS website, with or without using Amplify?

After diligently reading through the documentation provided by AWS which mainly focuses on React JS, I am feeling a bit lost. My goal is to set up the sign-in, sign-up, and login components but the process seems complex. I stumbled upon an alternative met ...

Utilizing JavaScript to send various arrays to a .NET web service

Hey everyone, I'm currently facing an issue with posting multiple arrays to a .net web service and here is the signature of the web service. <WebMethod()> _ Public Function Lib_Processor(ByVal w_vendor As String(), _ ...