What is the best approach to implementing value filtering from a URL in AngularJS?

Unfortunately, I am struggling with filtering the value obtained from the URL. Any ideas on how to fix it?

$scope.categoryFilter = function (products){

                if ($routeParams.categorySlug == products.category.seo_name){
                    return;
                }else {
                    return $scope.products;
                }
            };

Here are my routes:

when('/products/category/:categorySlug', {
            controller: 'ProductsListController',
            controllerAs: 'vm',
            templateUrl: '/static/templates/products/products_index.html'
        }).otherwise('/');

This is a snippet of the JSON data:

{
    "name": "Classic Pyjama Pants",
    "category": {
        "id": 2,
        "name": "Lingerie",
        "description": "",
        "visible": true,
        "products_count": 0,
        "products_count_cache": 0,
        "category_id_name": "2",
        "seo_name": "lingerie",
        "seo_title": "",
        "seo_desc": "",
        "seo_keywords": "",
        "lft": 2,
        "rght": 5,
        "tree_id": 3,
        "level": 1,
        "parent": {},
    "id": 920

In my template, I utilize the filter like this:

 <div class="catalog-item" ng-repeat="product in products |filter: categoryFilter">
        <div class="item-pre-title">
            Free shipping over $150
        </div>
        <div class="item-img">
            <a href="/products/{{ product.id }}/"><img ng-src="{{ product.picture[0].external_img_url }}" width="150px"
                                                       height="150px" alt=""></a>
        </div>
        <a href="/products/{{ product.id }}/" class="item-title">{{ product.name }}</a>
        <div class="item-price">
            <div class="price-old">{{ product.old_price }}</div>
            <b>{{ product.price }}</b>
        </div>
        <div class="item-footer">
            <a href="#" class="item-view"></a>
            <div class="item-sales-alert">
                Get discount
            </div>
        </div>
    </div>

A warning in the console pops up:

angular.js:11706 TypeError: Cannot read property 'seo_name' of null

I managed to resolve the TypeError issue but I can't get the filtering to work. Any suggestions?

UPDATE: I fixed the TypeError problem, but the filtering functionality is still not functioning properly.

Answer №1

To address the issue at hand, I made a modification by incorporating the following code in place of my previous Filter:

 $scope.categoryFilter = function (products){

                try {
                    if ($routeParams.categorySlug){
                       if ($routeParams.categorySlug == products.category.seo_name)
                            return products;
                    }else{
                        return $scope.products;
                    }
                }
                catch (TypeError) {
                   return;
                }};

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 significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Can you explain the distinction between $.param and JSON.Stringify?

I am encountering an issue with my code snippet: $http({ url: config.apiUrl + 'mail/Sendmail', method: 'POST', data: JSON.stringify({ Body: $scope.Message, ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

Setting the offset for panResponder with hooks: A step-by-step guide

While exploring a code example showcasing the use of panResponder for drag and drop actions in react native, I encountered an issue with item positioning. You can experiment with the code on this snack: The problem arises when dropping the item in the des ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...

Issue with vue.js not recognizing the 'require' function

I am a newcomer to Vue and I am trying to create a basic SPA using Vue without vue-router. Following the example of vue-2.0-simple-routing-example, I am attempting to load pages using require(dynamicPathToFile+'.vue'). However, this approach is n ...

Protractor: refreshing non-angular login page

Currently, I am experimenting with an angular webpage. However, before proceeding, I need to log in on a non-angular page that redirects to another non-angular one. Upon trying to execute my test by entering the username and password, the page unexpectedly ...

"Trouble arises with the match() function in relation to email regex validation

After retrieving the HTML content from a website with my function, I am using String.prototype.match along with a regex rule to extract email addresses from that page. However, the issue is that I am receiving a line that matches the regex but does not con ...

Error Message: "Unexpected use of Hook in react-hook-form"

I am still getting acquainted with react hook form so I have encountered a minor issue. To my surprise, Controllers are unable to handle values as numbers. At first, this was frustrating, but after some searching, I stumbled upon this helpful github issue ...

check if JSON value is not null

Display items in ng-repeat only when the value of a certain key is not empty. Here is the code snippet: <a class="item" href="#" ng-repeat="e in events | orderBy:'match_time'" ng-if="e.match_timer !== NaN && e.match_status !== ' ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Learn the process of dynamically adding new rows and assigning a distinct ng-model to each row

Does anyone know how to create a dynamic table in HTML with unique ng-models for each cell? I've tried the following code, but I'm struggling to figure out how to add ng-model. <!DOCTYPE html> <html> <head> <style> table, ...

Unable to cut a line shape in Three.js using THREE.ExtrudeGeometry for punching

Hey everyone, I'm brand new to Three.js I'm looking to cut out some shapes from a flat board using THREE.ExtrudeGeometry. Check out the code snippet below: // Code snippet here... In my example, I've included a circular shape and t ...

Guide on triggering a Bootstrap dropdown using an external button click

I have scoured almost half of the Internet, but I can't seem to find a clear example on how to accomplish this task. There are plenty of "solutions" out there, but nothing has been successful so far. Here is what I have attempted: $('#openner&a ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

Identifying when an image has finished loading without utilizing a directive specifically assigned to the image element

There is a plethora of examples in SO demonstrating how to utilize an angular directive to detect when an image has been loaded. These examples typically showcase a directive that is directly added to the img element like this: <img ng-src="myimage.jpg ...

AngularJS: Problem with Link rel stylesheet not being applied within the ui-view

THE LINK REL STYLESHEET CSS appears to be missing the css from login.html when viewed in the UI VIEW HTML <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <!-- IMPORT --> <link rel="styleshe ...

methods for detaching event listener from bootstrap carousel indicator elements

I am currently utilizing the bootstrap5 carousel feature and I am seeking a way to trigger a custom event when either the previous or next indicators are clicked. My goal is to stop the default bootstrap event from being triggered, however my attempts at v ...

Decoding JSON Data from Steam Inventory in PHP

My experience with json is limited, and I'm not entirely sure how to work with it. I am looking to retrieve all the items from the rgDescriptions table, but I'm unsure of the process. If anyone could provide guidance, I would greatly appreciate ...