Having trouble with your $scope.$watch not being triggered?

I am currently working on a table application that retrieves JSON data from a database. The data is passed to my app controller as a parameter and then filtered accordingly. Everything seems to be working well, except for the fact that I have a large amount of data (hundreds of thousands of objects). I have implemented search boxes to filter the data, but I am facing an issue where the $watch function does not get called when someone types into the search box. Am I overlooking something?

js:

var app = angular.module('SortingTables', ['ui.bootstrap']);
//Dependencies must map to string types which are then passed into the instance function

app.filter('startFrom', function () {
    return function (input, start) {
        start = +start; //parse to int
        return input.slice(start);
    };
});

app.controller('Ctrl', function ($scope, filterFilter, dataTable) {
    $scope.currentPage = 1;
    $scope.itemsPerPage = 25;
    $scope.totalItems = 0;
    $scope.predicate = '';
    $scope.searchBuffer = {
        $: ''
    };
    $scope.filtered;
    
    $scope.$watch('searchBuffer', function (term) {
        console.log('The watch on searchBuffer was called');
        $scope.filtered = filterFilter(dataTable, term);
        $scope.totalItems = $scope.filtered.length;
    });

    $scope.pageChanged = function () {
        $scope.currentRow = $scope.currentPage * $scope.itemsPerPage - $scope.itemsPerPage;
    };
});

html

<div ng-app="Components" ng-controller="Ctrl">
    <hr/>
    <table class="table table-striped">
        <tr>
            <th><a href="" ng-click="predicate = '\'Technical Owner\''; reverse=!reverse">Technical Owner</a>
                <br />
                <input type="search" ng-model="searchBuffer['Technical Owner']">
                </a>
            </th>
            <th><a href="" ng-click="predicate = 'Branch'; reverse=!reverse">Branch</a>
                <br />
                <input type="search" style="width: 40px" ng-model="searchBuffer.Branch">
                </a>
            </th>
            <th><a href="" ng-click="predicate = 'Branch'; reverse=!reverse">Sub Pillar</a>
                <br />
                <input type="search" ng-model="searchBuffer['Sub Pillar']">
                </a>
            </th>
            <th><a href="" ng-click="predicate = 'Path'; reverse=false">Path</a>
                <br />
                <input type="search" ng-model="searchBuffer.Path">
                </a>
            </th>
            <th><a href="" ng-click="predicate = 'Name'; reverse=!reverse">Name</a>
                <br />
                <input type="search" ng-model="searchBuffer.Name">
                </a>
            </th>
            <th><a href="" ng-click="predicate = 'Description'; reverse=!reverse">Description</a>
                <br />
                <input type="search" ng-model="searchBuffer.Description">
                </a>
            </th>
        </tr>
        <tr ng-repeat="ComponetOwner in filtered | startFrom:currentPage | orderBy:predicate:reverse | limitTo:itemsPerPage">
            <td>{{ComponetOwner["Technical Owner"]}}</td>
            <td>{{ComponetOwner.Branch}}</td>
            <td>{{ComponetOwner["Sub Pillar"]}}</td>
            <td>{{ComponetOwner.Path}}</td>
            <td>{{ComponetOwner.Name}}</td>
            <td>{{ComponetOwner.Description}}</td>
        </tr>
    </table>
    <pagination items-per-page="itemsPerPage" total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></pagination>
</div>

The $watch function is not being triggered when text is entered into the search box. Any insights on why this might be happening?

Answer №1

searchBuffer is considered an object in this scenario. To properly watch objects/arrays, the third optional argument of $watch must be set to 'true' in order to enable deep watching.

To learn more, check out: Tips for watching an object in Angular

Answer №2

If you want to keep an eye on all the objects within an object, you can utilize the $watchCollection method.

Another option is to set the third optional argument of your $watch function to true, although this won't go as deep as using $watchCollection.

For more information on this topic, check out this informative blog post:

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

Eliminate any null strings from an object by comparing the object's previous state with its updated state

I am currently implementing an exemptions scheduler using react-multi-date-picker. The react-multi-date-picker component is integrated within a react-table in the following manner: const [data, setData] = useState(0); const [dateValues, setDateValues] = us ...

Utilizing conditional formatting to set background colors in an HTML table

Our manufacturing company collects and documents data for the parts we produce. Currently, this information is logged on a spreadsheet with drawing dimensions in one column and actual measured values in another. The cell where the actual measured value i ...

What could be the reason this is not getting saved in the public directory and causing a 404 error on the network

Within connection.js on the backend, there is a 2nd code snippet located inside post.jsx on the front end. router.post("/upload", (req, res) => { if (req.file === null) { return res.status(400).json({ msg: "No file uploaded" }); } const f ...

Photographs housed within a pop-up window

My popover is causing me some trouble: I've got a popover that displays PHP-generated content without a fixed height, and I want to add an image inside it. The tooltip appears over my element like this: The problem is that if the image isn't pr ...

When adding values, they remain in their original positions

I am populating a select dropdown with options using AJAX. These options are added based on the selection made in another dropdown. The first function that appends the data: var appendto_c = function(appendto, value, curcode) { appendto.append("& ...

Guide on implementing the onSignInChanged event handler in a Chrome extension for Gmail

Here is a glimpse of the code from my Google Chrome extension: Manifest: "content_scripts": [ { "matches": [ "https://mail.google.com/*", "https://inbox.google.com/*" ], "js": ["js/jquery-3.2.1.min.js", "js/content.js"], "css": ["css/custom ...

NPM's twitter-v2 is throwing a 'TypeError: url_1.URL is not a constructor' error

Currently, my focus is on developing a Twitter bot. I am in the process of posting a Tweet using my account configured to work with Twitter API v2. This involves utilizing NPM's twitter-v2, along with Webpack 5.74.0 and the latest version of NodeJS. ...

While Advanced REST Client successfully retrieves an infinite JSON file from the AngularJS REST service, Postman encounters an error with the code ERR_INCOMPLETE_CHUNKED_ENCODING

I've encountered a peculiar issue. When making a REST call in Angular (using an app built with Ionic v1) to a Java endpoint, something goes awry and Chrome throws the following error: https://i.sstatic.net/1sxp7.png The code of interest is this Angul ...

When I apply properties in JavaScript, I find that I am unable to utilize the CSS "hover" feature

For a personal project I am currently working on, I decided to experiment with setting background colors using Javascript. However, I have encountered an issue where my CSS code that changes the hover property does not seem to work after implementing the J ...

v-autocomplete no selected option

Within my Vue.js 2 and Vuetify component, I am receiving the following data : [ { "anio": 2022, "__typename": "Grupo" }, { "anio": 2020, "__typename": "Grupo" }, { "anio": 2018, "__ ...

Using React and Redux: Sending a function to a child component, triggering it without a handler in the child component

I am experiencing difficulty sending an action through a callback in the code provided below. The action is not being sent as expected. However, if I add the Connected property to a handler like onClick, then the action is executed. How can I make my code ...

I'm experiencing an issue with Gravity Forms validating hidden fields, is there a solution for this problem?

On my webpage, there are four fields labeled A, B, C, and D. Each field has its own set of conditional logic that determines whether it should be visible or hidden. Let's say a user lands on this page and only field B is displayed while the others are ...

Where exactly is Bootstrap hiding?

Currently, I am in the process of working on a web application using Spring. My goal is to set up a bootstrap test table for the application and apply different themes to it. However, I am facing an issue where Bootstrap seems to be missing. I'm unsur ...

Using the jQuery plugin multiple times within one website

I have a decent understanding of jQuery and I'm in the process of developing a plugin. Specifically, it's a dropdown element that I'm working on. Everything functions correctly when there's only one dropdown on the site. However, when ...

When a new ajax function is added, the original Ajax code stops functioning

I've been working on getting the code below to function properly. It seems that when I test the code, two validation functions are working correctly. However, when I include the validateUsername() function along with the if statement in the code, ever ...

React-select: The default values will only be updated if they are initially set statically

Need help displaying a list of interests from backend data: profile : { interest: ["interest1", "interest2"], }; This is my implementation: import Creatable from "react-select/creatable"; class EditProfileInSettings exten ...

Issue with AngularJS directive: Isolated scope preventing values from being inserted into template

After setting up the directive below: angular.module('news.directives', []) .directive('newsArticle', function($location, $timeout) { return { restrict: 'AE', replace: 'true&apo ...

"How can I update a table in Flask using Chart.js and Pandas

I have developed a basic Flask application that includes a bar chart using Chart.js and a data table displayed below it. Check out the setup below: https://i.sstatic.net/QB6jQ.png (Live view: ) The bar chart I created counts the number of items for each ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

Exploring AngularJS's Unique Features: Isolated Scope and Controller Connection

Currently, I am diving into Angular and endeavoring to develop a Phone Message Log application utilizing directives. The concept is simple - the user inputs a message, clicks a button, and it gets displayed in a "Message" log below. The challenge I'm ...