The watch function remains inactive until it is triggered by an event

My current issue involves using $watch for pagination on my page. Unfortunately, the data is not appearing until I click on one of the buttons.

Below is the relevant code snippet:

.controller('AppCtrl', function ($scope, $modal, Faq) {
    $scope.filteredFaqData = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 5;
    $scope.maxSize = 5;
    $scope.faqData = [];
    $scope.faqData = Faq.getFaqs();
    $scope.$watch('currentPage + numPerPage', function () {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
            , end = begin + $scope.numPerPage;
        $scope.filteredFaqData = $scope.faqData.slice(begin, end);
    });
})

In this setup, the data is retrieved in $scope.faqData from the service. However, the $scope.filteredFaqData remains empty until I actually interact with the paging tabs.

Answer №1

Perhaps this approach will solve the issue:

.controller('AppCtrl', function ($scope, $modal, Faq) {

    //create a reusable function
    var updateFilteredData = function () {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage),
            end = begin + $scope.numPerPage;

        $scope.filteredFaqData = $scope.faqData.slice(begin, end);
    };

    $scope.filteredFaqData = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 5;
    $scope.maxSize = 5;
    $scope.faqData = Faq.getFaqs();

    $scope.$watchGroup(['currentPage', 'numPerPage'], function () {
        //invoke the update function
        updateFilteredData();
    });

    //initial invocation
    updateFilteredData();
});

Note: It's advisable to use watchGroup as it aligns with Angular's approach for achieving the desired functionality (documentation).

Answer №2

My function Faq.getFaqs() was running asynchronously, causing an issue where no data would display when the page loaded for the first time. To solve this, I implemented a $timeout to delay the $watch functionality, which successfully resolved the issue.

Below is the updated code snippet:

$scope.filteredFaqData = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.faqData = [];

$scope.faqData = Faq.getFaqs();
$timeout(function lateDisplay() {
    $scope.$watchGroup(['currentPage', 'numPerPage'], function(newValues, oldValues, scope) {
        var begin = ((newValues[0] - 1) * newValues[1]);
        var end = begin + newValues[1];

        $scope.filteredFaqData = $scope.faqData.slice(begin, end);
    });
}, 100);

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

A method for sequentially exploding a nested JSON with index by utilizing posexplode_outer

I'm facing an issue with my nested JSON data that I want to expand using the posexplode_outer function in my code snippet below: def flatten_df(nested_df): for column in nested_df.columns: array_cols = [c[0] for c in nested_df.dtypes if c ...

Exploring uncharted territory with the Navigator component in React Native

I am experiencing an issue with undefined navigator when using React Native MessageTabs: _onPressItem = (item) => { const { navigate } = this.props.navigation; //console.log(JSON.stringify(item)); navigate('SingleConversation', {id ...

What strategies are most effective for managing JSON containing keys without quotes?

I rely on a third-party service for my website, which sends data back in a simple JSON format. The issue I am facing is that the JSON key names are not enclosed in quotes. For instance, both ServiceStack.Text.JsonObject.Parse and System.Json.JsonObject.Pa ...

Having difficulty executing the multichain-node npm module on the client side (browser)

let blockchain = require("blockchain-node")({ port: 6001, host:'localhost', user:'myuser', pass:'mypassword' }); blockchain.getInfo((error,info) => { if(error){ throw error; } consol ...

What is the best method for converting this intricate JSON data into a structured SQL database table?

Within my JSON data, extracted from a care management system for automated KPI gathering, each resident has a unique set of information. Here is an example of the data for one resident: { "ServiceUserDetails": [ { "CellDetails": [ ...

What is the best way to create a directive that will hide a div when clicking anywhere on the

Today is my first time attempting to write a directive. I am currently working on a directive that will hide my div element. Below is the HTML code: <div id="loggedIn" close-logged-in class="fade-show-hide" ng-show="loggedInOpened" ng-cloak> @Html.P ...

Exploring the Power of Laravel 5.5 and Vue.js 2.x for Efficient API Calls

Currently, I am working on a Laravel 5.5 project locally that incorporates Vue.js 2.5.9 with XAMP Server. One of the tasks I have is to load certain information onto the DOM and then refresh it upon clicking the "Refresh" button. However, there seems to ...

Display multiple markers on a Google Map using google-map-react library

I am currently struggling to display markers on my Google Map using the map function. I have tried various approaches but nothing seems to work. Could there be limitations that I'm not aware of, or am I overlooking something critical? I experimented w ...

Issue with connect() method in React-Redux resulting in a TypeError

Currently immersed in the Redux tutorial by Dan Abramov, specifically on chapter 27 - Generating containers with connect(), encountering a rather peculiar bug: To start off, I define these two functions: const mapStateToProps = (state) => { return ...

In my current project, I am implementing a feature in Angular 6 to close a Bootstrap modal once the server successfully receives the necessary data

Here, I am working on creating the content for a CRUD component that saves data as needed. My goal is to make the modal disappear once the data is submitted. <div class="container"> <div class="table-wrapper"> <div class="table-ti ...

Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released. However, I encountered an issue wit ...

What is the best way to export assets into a React Native JS file?

After watching a video on YouTube, I noticed that at 3:20 the individual in the video quickly exported multiple assets into a file without providing any explanation. Can someone please view this specific moment in the video and clarify how this person mana ...

Serialization and deserialization of Jackson Arrays

I encountered an issue with my Jackson string that looks like this: { "Response":{ "users":[{"userId":"1", "userName":"User 1"},{"userId":"2", "userName":"User 1"}] } } I have the following classes defined, public class Response { private List< ...

Explore JSON data and populate dropdown and select elements with corresponding details

Looking for advice on how to separate bank details into a select box and employee details into a table using the JSON provided. Unsure of how to iterate through each section to place them in their required sections. If anyone has suggestions on how to acc ...

Breaking the website with an HTML comment

Upon clicking a link to another page, I encountered the error message "Failed to execute 'insertBefore' on 'Node." Here is the code snippet that was causing the issue: <template name="reminderPage"> <a href="/newRemind">New! ...

Enhance your search experience with Vue.js by highlighting important keywords across multiple search

I'm working on implementing a search feature that will bold the matching parts. For example, if I have the name 'John' and search for 'Jo Joh' in the same string, I want it to bold the part of 'John' that has the most mat ...

Sending an Angular $http post request to a MVC action but the parameter is coming through as

After posting this content: $http.post(Common.blog.save, { blog: blog }) .then(saveBlogComplete) .catch(function(message) { }); The Fiddler output I receive is as follows: {"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\ ...

AngularJS directive failing to execute

Check out this directive: app.directive('changeImage', function() { return { restrict: 'A', link: function(scope, element, attrs) { alert('here'); $(element).hover(function() { ...

Exploring the multidimensional statistical capabilities in the sweep function of R programming

Is there a way to manipulate the first two dimensions of an array based on the values in the first column of the third dimension? For instance, consider the following array: Input array: a <- array(1:24,c(4,3,2)) > a , , 1 [,1] [,2] [,3] [1,] ...

How can you modify two distinct append values individually in AngularJS?

I am facing a challenge with two-way binding. I want to be able to change the name of each appended value from the displayed field options. When I try to append two additional fields, I am unable to change the name of each multiple field from the single fi ...