The view in Angular remains unaffected even when the object in the scope is altered

Screencast Video:
Javascript Source File: (located at the bottom)
Demonstration of the Issue:

I have been facing a persistent issue that I am struggling to resolve. My goal is to allow users to sort database results by clicking on radio buttons with specific filters.

Upon clicking a radio button, the console shows that the correct URL is fetched using AJAX, but unfortunately, the list does not update in the view.

The page functions correctly upon initial load (without any sorting filters applied).

The Controller:

FontGet.controller('mainController', ['$scope', 'FontService', '$location', '$rootScope', '$routeParams', function($scope, FontService, $location, $rootScope, $routeParams) {
    $rootScope.hideFatMenu = false;
    $scope.navCollapsed = true;
    $scope.isSettingsCollapsed = true;
    $rootScope.header = "Welcome to FontGet.com!";
    $scope.sortBy = 'new';

    $scope.fonts = {
        total: 0,
        per_page: 10,
        current_page: ((typeof($routeParams.page) !== 'undefined') ? $routeParams.page : 1),
        loading: true
    };

    $scope.setPage = function() {
        FontService.call('fonts', { page: $scope.fonts.current_page, sort: $scope.sortBy }).then( function(data) {
            $scope.fonts = data.data;
            $scope.fonts.loading = false;

            document.body.scrollTop = document.documentElement.scrollTop = 0;
        });
    };


    $scope.$watch("sortBy", function(value) {
        $scope.setPage();
    });

    $scope.$watch("searchQuery", function(value) {
        if (value) {
            $location.path("/search/" + value);
        }
    });


    $scope.categories = FontService.categories();
    $scope.setPage();
}]);

The View Template:

<div class="fontdd" ng-repeat="font in fonts.data" >
    <!-- Content goes here. This populates correctly upon initial page load -->
</div>

The Sorting Radio Buttons:

<ul class="radiobtns">
    <li>
        <div class="radio-btn">
            <input type="radio" value="value-1" id="rc1" name="rc1" ng-model="sorts" ng-change="sortBy = 'popular'">
            <label for="rc1" >Popularity</label>
        </div>
    </li>
    <li>
        <div class="radio-btn">
            <input type="radio" value="value-2" id="rc2" name="rc1" ng-model="sorts" ng-change="sortBy = 'trending'">
            <label for="rc2">Trending</label>
        </div>
    </li>
    <li>
        <div class="radio-btn">
            <input type="radio" value="value-4" id="rc4" name="rc1" checked="checked" ng-model="sorts" ng-change="sortBy = 'new'">
            <label for="rc4">Newest</label>
        </div>
    </li>
    <li>
        <div class="radio-btn">
            <input type="radio" value="value-3" id="rc3" name="rc1" ng-model="sorts" ng-change="sortBy = 'alphabetical'">
            <label for="rc3">Alphabetical</label>
        </div>
    </li>
</ul>

You may notice that the ng-model for the radio buttons is not assigned to sortBy. This decision was made to prevent the AJAX call from being triggered multiple times (which occurs when linked to sortBy).

Answer №1

Instead of relying on a $scope.$watch function to monitor changes in the sortBy scope variable, consider updating your sort buttons' ng-change event like this:

    <div class="radio-btn">
        <input type="radio" value="value-1" id="rc1" name="rc1" ng-model="sorts" ng-change="Sort('popular')">
        <label for="rc1" >Popularity</label>
    </div>

To handle the sorting logic, implement a Sort() function in your controller:

$scope.Sort = function(sortBy) {
   $scope.sortBy = sortBy;
   $scope.setPage();
}

Rather than using $watch, you can achieve the same result by directly calling a function with the necessary parameters.

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

What is the best path to take for my website: a related path or an absolute path?

I'm currently working on a website project for a client and I'm considering the best approach to ensure security. If you have any insights or recommendations on how to make the website more secure, please let me know! Thank you in advance. For i ...

Retrieve the JSON data from the server's response

{"identifier":"2231f87c-a62c-4c2c-8f5d-b76d11942301"} After alerting the response data, I discovered the code snippet shown above. Now, how can I retrieve the value of the identifier? The controller is set up to return like this: return Json( new { ...

Retrieving data from router in Angular

I have been working on a web application using Angular, and I have implemented a fixed header in the index.html file. The header appears on every page, with content injected through a ui-view. However, I now want to display this header only after the user ...

having trouble accessing a JavaScript array in AngularJS

Hey there, I'm currently working on a web application using AngularJS and I'm facing an issue with querying arrays. Check out the code snippet below: var angulararray = []; bindleaselistings.bindleaselistingsmethod().then(function(response) { ...

"Utilizing Typescript and React to set a property's value based on another prop: A step-by

Is there a way to create a dynamic prop type in React? I have an Alert component with various actions, such as clicking on different components like Button or Link. I am looking for a solution like this: <Alert actions={[{ component: Link, props: { /* ...

Tips for positioning the cursor at the beginning of text and shifting the focus to the start while utilizing the MaterialUI Input component

I have scoured various online forums for a solution to this issue, but none of the suggestions seem to work. Although I managed to position the cursor at the beginning of the text, it did not shift the focus accordingly. Here is the code snippet for the co ...

Exploring the _embedded section within a Json Response

Having difficulty accessing the _embedded property within Json in Angular. Wondering if it's even possible. The Json response, created using Spring-Data-Jpa, is structured like this: { "_embedded": { "reviews": [ { "author": " ...

Retrieval of request in iframe URL

Currently, a third party is displaying my URL within their iframe. They are limited in flexibility and simply hard code the URL I provide them with. <iframe url="https://firstURL.com"></iframe> Now, I need to distinguish between two groups of ...

The LINQ to Entities software is unable to identify the method 'Newtonsoft.Json.Linq.JToken get_Item(System.String)' method

Below is a working code snippet: string data = Encoding.UTF8.GetString(eventData.GetBytes()); JObject o = JObject.Parse(data); var disp = db.Dispositivos .Where(p => p.ClaveDispositivo == "UM5WOkRIFtS9dWbM5f1YM/ncpdrpSYrh3zND9Y/YHM4="); if(disp.T ...

Retrieve the JSON string from the AJAX response text

Upon receiving an Ajax response, the text I get is as follows: "<json> <![CDATA[ {"status":true,"filterMap":{ "summary":"Summary","total":"Total","myProfileMsg":"Opening my profile, please wait","cgBase":"CG Base","export1":"Export"}} ]]> &l ...

Passing a sophisticated data structure to the controller, where some of the attributes are derived from a separate partial view

I have a model for my view that includes information about appointments and their recurrence. It looks something like this: public partial class AppointmentModel { public appointment Appointment { get; set; } public appointmentRecurrence Rec ...

Enter information to accompany your images in the description box

After browsing through numerous websites tonight, I stumbled upon this code. My goal is to create a photo upload page on Google Drive and set up a dropbox for it. I'm facing an issue where the information inputted into my placeholder box (city and ye ...

"Deleting a specific row from a SQL Server using Node.js: Step-by-Step Guide

Currently, my setup involves using nodeJs as the backend language and sql server as the database. While I have managed to delete whole table rows from the database successfully, I am facing a challenge when it comes to deleting a specific row. Here is the ...

Tips for creating a well-formatted json string with a single space after each comma using Gson

Below is a snippet of code where I am creating a JSON string using Gson: private String generateData(Map<String, Map<Integer, Set<Integer>>> nodeTable, int i) { JsonObject jsonObject = new JsonObject(); Set<Integer> pp = n ...

Storing List as a JSON array in PostgreSQL

I am facing an issue with saving a List private List<Lesson> lessons; to a PostgreSQL database column. The data type of the column is either _json or json[] (JSON array). However, when I try to save it, I encounter one of the following errors: ERR ...

What is the process for importing a map from an external JSON file?

I have a JSON file with the following configuration data: { "config1": { //this is like a map "a": [ "string1", "string2"], "b": [ "string1", "string2"] } } Previously, before transitioning to TypeScript, the code below worked: import ...

Tips on ensuring CSS is properly loaded on a Django HTML page

Despite numerous attempts, I cannot get my CSS to render properly on any of the HTML pages within a Django project. I've tried various solutions from Stack Overflow, such as adding the following code snippet: <link rel="stylesheet" href=& ...

Tips for customizing Facebook like button on a one-page website featuring dynamic content using AJAX technology

I'm facing an issue with a single-page website where the HTML is loaded and parsed only once. I have dynamic content, such as products, that I want to add a like button to. The challenge is ensuring that the like content is specific to the dynamically ...

Codeigniter raises an error message stating, "No file selected for upload," in cases where data is transmitted via Ajax

Having trouble inserting form data using Ajax and Codeigniter - encountering a 'You did not select a file to upload' error specifically with file uploads. Need help passing input file data through jQuery ajax. Below is the jQuery code snippet: ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...