Best method to extract an item from an array using AngularJS

Just dipping my toes into AngularJS and pondering on a more streamlined approach:

Currently, I have a factory that supplies me with an array of product objects. (For now, this data is hardcoded but will eventually be fetched from a RESTful API.)

app.factory('Products', function(){
    var products = [
        { slug: 'wireframe-kit', name: 'Wireframe Kit', price: 27 },
        { slug: 'ui-kit', name: 'UI Kit', price: 29 },
        { slug: 'ui-icons', name: 'UI Icons', price: 39 }
    ];
    return products;
});

For instance, when navigating to a route like /product/wireframe-kit, here's how the routing is currently configured:

app.config(function($routeProvider){
    $routeProvider.
        when('/product/:slug', {
            templateUrl: 'template/product.html',
            controller: 'productController'
        });
    }
}); 

To fetch the correct product based on the URL slug in the controller, I am presently utilizing a forEach loop:

app.controller('productController', function($scope, $routeParams, Products){
    Products.forEach(function(product){
        if( product.slug == $routeParams.slug) {
            $scope.product = product;
        }
    });
});

I'm hesitant about the efficiency of the forEach loop in the controller - there must be a smoother way to extract the desired object from the products array. Any suggestions?

Answer №1

If we were to establish a REST API in a practical manner, it would look something like this:

/items - representing the 'collection'

and /items/:id - representing the 'model'

Since you are utilizing static data, consider placing the data on the server as static files to mirror these structures within relevant web directories.

Subsequently, with Angular, configure the routes to perform GET requests for these 'endpoints'

  • /items/ - retrieves $scope.collection
  • /items/<id of products> - retrieves $scope.model

Answer №2

If every product in your api has a unique slug, consider updating your api to return an object. This way, you can easily access products by their key (slug) name:

app.factory('Products', function(){
    var products = {
        'wireframe-kit': { slug: 'wireframe-kit', name: 'Wireframe Kit', price: 27 },
        'ui-kit': { slug: 'ui-kit', name: 'UI Kit', price: 29 },
        'ui-icons': { slug: 'ui-icons', name: 'UI Icons', price: 39 }
    };
    return products;
});


app.controller('productController', function($scope, $routeParams, Products){
    $scope.product = Products[$routeParams.slug];
});

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 reason for the success of this OpenMP code on Linux, while encountering issues on Windows?

Update: Issue resolved! I discovered that Windows limits the stack size, causing my buffer to not fit; unlike Linux. Additionally, I found out that I was accessing memory outside of my array by mistake. To set the stack size with gcc on Windows, you can us ...

Launching an AngularJS project: seeding versus scripting

I am currently in the process of developing a small AngularJS application for deployment on a web server, but I am struggling to grasp the difference between utilizing Angular's startup seed as opposed to directly linking the script in the HTML, such ...

Using Angular.js Select with ngOptions to group options under a specific label

Exploring the wonders of Angular.js, I have a query regarding ngOptions: Can optgroups be labeled? Imagine two entities - cars and garages. cars = [ {"id": 1, "name": "Diablo", "color": "red", "garageId": 1}, {"id": 2, "name": "Countach", "color" ...

A guide on consolidating all app.use statements into a single shared file

My application's starting point, the index file, contains multiple instances of app.use. For example: app.use( if (!req.contextToken && req.contextTokenchecked) { req.queryToFirebase = false; req.contextTokenchecked = tru ...

How to Toggle the :invalid State to True on a Dropdown Element Using JQuery

$("#select_id").is(':invalid') false Is there a way to change it to true? $("#select_id").addClass(':invalid'); $("#select_id").prop('invalid',true) Unfortunately, this method does not seem t ...

Easily Convert Square Bracket Notation to Dot Notation in JavaScript/Typescript for Quick Replacement

Currently, I am reviewing some code that includes unnecessary square bracket notations. To improve code comprehension, my aim is to transform instances like abc[3]['prop']["subprop"] into abc[3].prop.subprop. I have been able to achiev ...

Invoking the .html(result) function multiple times within the AJAX success callback

I have implemented this code in my template to handle my ajax request: <script> $(document).ready(function() { $("#send-mail-button").click(function(e){ e.preventDefault(); var nameVar = $('#name&apo ...

Verify a document located on another server

My objective is to prompt the user to download a file generated by my script and upload it onto their server (this functionality has been successfully implemented). The purpose of this task is to confirm that the user can indeed upload files to the website ...

What is the best way to automatically log out a user once their session cookie has expired during an online exam?

While developing an MVC ExpressJS Test app, I encountered an issue with auto-logout functionality for users who stop answering test questions. The error message "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" keeps app ...

Find out the index of a div within an array

Curious about determining the position of a div in an argument? For instance, if there are multiple divs with the same name: <div class="woot"></div> <div class="woot"></div> <div class="woot"></div> <div class="woot ...

Navigation for GitHub pages

I've been working on this for what feels like forever. The persistent Error 404 I'm encountering is with the /Quest/questlist.txt file. https://i.sstatic.net/NYYRa.png Here's the code snippet I've been using: ``// QuestCarousel.tsx ...

Creating dynamic routes in Rect JS using API data

Looking for a way to generate routes data dynamically from an API in my React JS project. Below is the static JSON data I currently have in my "routes". How can I update this to pull data dynamically from an API? import React from 'react'; ...

"Is there a similar function in axios to jquery's ajaxComplete

Just began delving into axios and gotta say, it's pretty awesome! I've got a burning question that I can't seem to find the answer to. Maybe there isn't one? In jQuery ajax, there's this handy method called ajaxComplete. I'm ...

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...

I am encountering an issue with retrieving API JSON data in NextJS where I am receiving an

Instead of receiving data in my console log, I am seeing undefined. This is my Index.js file (located in the pages folder) import Head from "next/head"; import Link from "next/link"; import axios from "axios"; import Test fro ...

What is the reason my answer for the powerset problem is flawed? Both my recursive and iterative methods are attached for review

How can I generate all possible subsets from an array of unique integers? For instance, if I have powerSet[1,2,3], the expected output should be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]] I've tried a recursive approach: function powerset(arr ...

If the td element contains text, add a comma (,) and wrap the text in HTML tags. If there

Currently diving into some jQuery code and have come across a few uncertainties. Here is what I've managed to put together so far: var html = ''; data.entities.forEach(function (value, index, array) { html += index !== data.entities.len ...

Exploring Angular's Ng-Repeat for Nested Associations

My program is set up with the following connections: A :review contains many :comments, where each comment belongs to a :user who has a :username. However, when I try to display this information in my Angular view using the code below, it does not work as ...

Add up all the numbers within an array by continuously adding them together

I am currently working on a program for my class that is designed to calculate the sum of all integers in an array using recursion. Below is the code snippet I have developed so far: public class SumOfArray { private int[] a; private int n; private int r ...