Numerous perspectives within an angular.js application

Issue

I'm currently working on creating a product list with the following initial features:

  • Server-side pagination
  • Server-side filtering

I am facing several challenges with my current setup, but the main issue is that I can't figure out how to separate the views effectively. Currently, whenever the page is changed, the category list gets updated (and any checked items get unchecked).

Is there a way for me to load the category list only when the page initially loads?

Thank you

Code

index.html:

<div ng-app="relv">
    <div ng-view></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="//cdn.jsdelivr.net/angularjs/1.0.2/angular-resource.min.js"></script>
<script src="/angular/app.js"></script>
<script src="/angular/services.js"></script>
<script src="/angular/controllers.js"></script>
<script src="/angular/filters.js"></script>
<script src="/angular/directives.js"></script>

app.js:

'use strict';
angular.module('relv', ['relv.filters', 'relv.services', 'relv.directives']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/products', {templateUrl: '/angular/partials/product_list.html', controller: ProductListCtrl});
    $routeProvider.when('/products/:page', {templateUrl: '/angular/partials/product_list.html', controller: ProductListCtrl});
    $routeProvider.otherwise({redirectTo: '/products'});
  }]);

product_list.html:

<div id="category_list">
    <label ng-repeat="category in categories">
        <input type="checkbox" name="category" ng-model="filterCategories[category.id]"> {{ category.name }}
    </label>
</div>
{{ filterCategories }}

Product list, page {{ page }}.
<br><br>
<ul>
    <li ng-repeat="product in products">
        <a href="#/product/{{ product.id }}">{{ product.name }}</a><br>
        <span ng-repeat="category in product.categories">{{ category.name }}</span>
    </li>
</ul>

<a href="#/products/{{ page-1 }}">Previous page</a>
<a href="#/products/{{ page+1 }}">Next page</a>

controllers.js:

'use strict';

function ProductListCtrl($routeParams, $scope, ProductList, CategoryList) {
    $scope.page = $routeParams.page ? parseInt($routeParams.page) : 1;
    $scope.products = ProductList.query({'page': $scope.page});
    $scope.categories = CategoryList.query();
    $scope.filterCategories = {};
}
ProductListCtrl.$inject = ['$routeParams', '$scope', 'ProductList', 'CategoryList'];

services:js:

'use strict';

angular.module('relv.services', ['ngResource']).
    factory('Product', function($resource){
        return $resource('http://endpoint/api_dev.php/products/:productId.json', {}, {
            query: {method:'GET', params:{lang:'en'}, isArray:false}
        });
    }).
    factory('ProductList', function($resource){
        return $resource('http://endpoint/api_dev.php/products.json', {}, {
            query: {method:'GET', params:{lang:'en', page: ':page'}, isArray:true}
        });
    }).
    factory('CategoryList', function($resource){
        return $resource('http://endpoint/api_dev.php/categories.json', {}, {
            query: {method:'GET', params:{lang:'en'}, isArray:true}
        });
    })
;

Answer №1

If you want the category list to always be visible, insert this code into your index.html file, above <ng-view>:

<div id="category_list">
    <label ng-repeat="category in categories">
        <input type="checkbox" name="category" ng-model="filterCategories[category.id]"> {{ category.name }}
    </label>
</div>
{{ filterCategories }}

In this way, the category list will remain static even when navigating between routes within the application.

Update: Place the code responsible for loading the categories inside a new controller:

function CategoryCtrl($scope, CategoryList) {
    $scope.categories = CategoryList.query();
    $scope.filterCategories = {};
}

index.html:

<div ng-controller="CategoryCtrl">
  <div id="category_list">
     <label ng-repeat="category in categories">
        <input type="checkbox" name="category" ng-model="filterCategories[category.id]"> {{ category.name }}
     </label>
  </div>
{{ filterCategories }}
</div>

<div ng-app="relv">
    <div ng-view></div>
</div>

Answer №2

Whenever you switch between views, the entire page's HTML is swapped out, including the checkboxes.

Split the HTML code into two separate views: master and detail (a minor adjustment).

The Master view should contain the checkboxes and pager, while the Detail view should display the product list.

By doing this, AngularJS will only swap out the HTML related to the products, leaving the categories untouched.

This specific issue has been discussed in Google forums.

Updated: Example of moving categories outside of the detail view

<div id="category_list">
    <label ng-repeat="category in categories">
        <input type="checkbox" name="category" ng-model="filterCategories[category.id]"> {{ category.name }}
    </label>
</div>
{{ filterCategories }}

<div ng-app="relv">
    <div ng-view></div>
</div>


<a href="#/products/{{ page-1 }}">Previous page</a>
<a href="#/products/{{ page+1 }}">Next page</a>


<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
...

Alternatively

In this scenario, forego using views altogether. Instead, organize your products into groups and update the data using a repeater (similar to paging, refer to another example in my response here).

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

Ensure that a div remains active even after it has been selected through AJAX using jQuery

I am currently utilizing ajax to display information from a database. The application I am working on is a chat app, where clicking on a specific conversation will append the data to a view. The structure of my conversation div is as follows: <div clas ...

Node.js setInterval is a method used to repeatedly execute a function

I have a code snippet for an http request that is supposed to run every one minute. However, I am encountering an issue with the following error: "Error: listen EADDRINUSE". Here is my current code: var express = require("express"); var app = express(); v ...

In Vue3, I utilize the Provide and Inject feature to handle data changes without triggering a visual update. Instead, I apply a filter() function to remove an item from an

I am currently testing the usage of the provide and inject methods. I have placed the datas and del-function in the parent component to provide, and in the child component, I am dynamically rendering using v-for='data' in datas. The objective I ...

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Expanding the width of a Datatables within a Bootstrap modal

While working on my modal, I encountered an issue with the width of Datatables. Despite trying to adjust it to fit the modal size, it appears like this: Below is the jQuery code calling the Datatables: function retrieveTags(){ var identifier = $(&a ...

Angular directive ceases to trigger

I am currently working on implementing an infinite scrolling directive. Initially, when the page loads and I start scrolling, I can see the console log. However, after the first scroll, it stops working. It seems like it only triggers once. Can anyone poi ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Encountering Error with NodeJS Typescript: Issue with loading ES Module when running sls offline command

I have come up with a unique solution using NodeJS, Typescript, and Serverless framework to build AWS Lambdas. To debug it locally in VS Code, I use the serverless-offline library/plugin. You can find my project on GitHub here However, when I run the comm ...

What is the most efficient method for executing over 1,000 queries on MongoDB using nodejs?

I have a task to run around 1,000 queries on MongoDB in order to check for matches on a specific object property. I must confess that my code is quite amateurish, but I am open to any suggestions on how to improve its efficiency. The current version works ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

Difficulty in transferring a variable from my JavaScript file to my PHP file

Currently, I am utilizing the Instascan API to scan QR codes with the intention of sending the scanned content to my PHP file. However, regardless of whether I use POST or GET methods, the PHP file does not seem to recognize them and keeps expecting either ...

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Tips for implementing $setValidity with ng-if for the same field in Angular

Hey there, I'm currently facing an issue with using form.form_field.$setValidity on an ng-if tagged field. When testing out the code, I encountered the following error: angular.js:13642 TypeError: Cannot read property '$setValidity' of unde ...

Customizing column specifications in Angular's UI-Grid

Imagine having the following dataset: let data = [ {name: 'bob', bornOn: 1510174615339}, {name: 'mary', bornOn: 1510164615339} ] When passed into a ui-grid, it results in 2 columns. To convert the epoch time to a human-readable fo ...

Share JSON data across functions by calling a function

I am currently working on a project where I need to load JSON using a JavaScript function and then make the loaded JSON objects accessible to other functions in the same namespace. However, I have encountered some difficulties in achieving this. Even after ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

What is the process of encoding a String in AngularJS?

Utilizing Angularjs for sending a GET HTTP request to the server, which is then responded to by the Spring MVC framework. Below is a snippet of code depicting how the URL is built in Angular: var name = "myname"; var query= "wo?d"; var url = "/search/"+qu ...

Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using: <input type="text" placeholder="Search people here ...