Troubleshooting problem with AngularJS orderBy

Excuse me if this comes across as silly.

I'm encountering a problem that is reminiscent of this question. While the accepted solution worked, it brought up another issue: Angular doesn't render a new object added to the array.

  app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
      $scope.posts = $filter('orderBy')(posts.posts, '-votes')
    }
  ]

This is my add function:

    o.addPost = function(post) {
        return $http.post('/posts', post).success(function(data) {
          o.posts.push(data)
        })
    }

Is there anything I can do to address this?

UPDATE: Here's what I've decided on:

  o.addPost = function(post) {
      return $http.post('/posts', post)
  }

  app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
      $scope.posts = $filter('orderBy')(posts.posts, '-votes')

      $scope.addPost = function() {
        posts.addPost(param).then(function(response) {
        $scope.posts.push(response.data)
      })
    }
  ]

Answer №1

Instead of unwrapping the promise inside the factory, simply return the HTTP response.

o.addPost = function(post) {
    return $http.post('/posts', post);
}

Next, invoke the addPost method within the factory and handle the promise accordingly.

app.controller('MainCtrl', [
    '$scope',
    '$filter',
    'posts',
    function($scope, $filter, posts) {
        var params = {};
        posts.addPost(params).then(function(data) {
            $scope.posts = $filter('orderBy')(data, '-votes')
        })

    }
])

Answer №2

Angular will only trigger for changes in instances. If you simply use push or splice to modify the array, the filter will not be activated.

To ensure that the filter is fired, you can follow these steps to assign a new instance to the array.

o.addPost = function(post) {
    return $http.post('/posts', post).success(function(data) {
      o.posts.push(data);
      o.posts = o.posts.slice();    // By doing this, a new instance of the array is created and the filter will be triggered.
    })
}

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

Transform a series of items into an array

I have a task where I need to create a function that takes a list as an argument and returns its elements in an array format. For instance, if the input is: {value: 1, rest: {value: 2, rest: null}} Then, the expected output should be: [1, 2] This is my ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

Skrollr triggers a fade-in effect once the user reaches a specific distance from the bottom of the

Using skrollr, I have a div positioned at the bottom of some content that I want to fade in once the screen reaches its level. I attempted various examples found on their cheat sheet but had no success. This div is situated above the footer (500px from t ...

Validation needed for data list option

Here are all the details <form action="order.php" method="post" name="myForm" onsubmit="return(validate());"> <input type="text" list="From" name="From" autocomplete="off" placeholder="From Place"> <datalist id="From"> <option valu ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Obtaining music information from an input type file in ReactJs

I have a file input field that accepts only music files. I'm looking to extract information about the music, such as the singer's name or album cover photo. <input type="file" className="popup-content--file" accept="au ...

What are the steps for utilizing the skrollr library to manipulate text within a div without it being

I'm a beginner in html, css, and javascript and I'm trying to create my first one-page website using the skrollr library. However, I'm facing an issue where the content in my second div is not displaying properly and is hidden behind the fir ...

Is the user currently browsing the 'Home screen webpage' or using the Safari browser?

In JavaScript, is there a method to determine if the user has accessed the website from their home screen after adding it to their home screen, or if they are browsing via Safari as usual? ...

Combining two items from separate arrays

How can I efficiently merge objects that share the same index in two different arrays of objects? Below is the first array const countries = [ { "name": "Sweden", "nativeName": "Sverige" }, ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

How can you identify the resume of a web application once you return from opening the camera?

I'm working on a web application that utilizes the camera by following steps from this solution: How to access a mobile phone's camera using a web app? However, I am trying to figure out how to implement a callback function once the user return ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

Creating a dynamic user interface with multiple tab navigations using jQuery on a single web

On my current HTML page, I am facing an issue with multiple tab navigations. When I click on one navigation, it also affects the other tab navigations. I cannot seem to find a way to only affect the tab navigation that I am clicking on without hiding the ...

Ways to retrieve information from elements using document.getElementsByClassName

Currently, I am trying to determine whether a specific CSS class is being used within the DOM. To do this, I've utilized the following code snippet: var x = document.getElementsByClassName('classname'); Upon inspecting the output of variab ...

Unable to find 'react/lib/merge' module

I'm currently working on a React project and utilizing Babel and Webpack. Within one of my files, I have this require statement: var merge = require('react/lib/merge'); Unfortunately, I'm encountering the following error: ERROR in . ...

What is the purpose of passing the Promise constructor as a second argument in knex migration examples?

When using Knex, migration files are used to make changes to the database structure, and they can be applied or rolled back. To create a new migration file, you can use the following command in the cli: knex migrate:make migration_name After running this ...

What is the reason for JSHint alerting me about utilizing 'this' in a callback function?

While working in my IDE (Cloud 9), I frequently receive warnings from JSHint alerting me to errors in my code. It is important to me to address these issues promptly, however, there is one warning that has stumped me: $("#component-manager tr:not(.edit-co ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

Simple solution for storing key-value pairs temporarily in a form using JQuery

Is there an elegant method to temporarily store an array of string values in a form? In my article editing form, users can add tags as string values. I don't want these tags to be persisted until the user saves the entire article, so I require a way ...