Utilizing the filter function iteratively within an Angular factory component

I am facing an issue where I have a factory with 2 controllers. The first controller returns an entire array, while the second controller is supposed to return only one item based on a specific filtering expression. I need to extract the last two parameters from the URL, loop through the array, identify the array item that matches the value of a specific attribute, and then return that element with all its attributes and values. This part is not a problem, but I'm unsure how to achieve this in Angular if I want to filter within the array itself inside the factory.

If you need further clarification, I have included a link to a JSFiddle that provides a brief explanation in the HTML section: https://jsfiddle.net/65224mk6/

Below are my current factory and controllers in case you prefer not to visit the link:

portApp.factory("workFactory", function() {
    var selected = [];
    var works = [
    {
        Title: "Sprite",
        subTitle: "",
        Link: "sprite",
        Thumbnail: "img/portfolio02.png",
        Image: "img/ismont.png"
    },
    {
        Title: "Pepsi",
        subTitle: "Kristályvíz",
        Link: "pepsi",
        Thumbnail: "img/portfolio03.png",
        Image: "img/sanofimont.png"
    }
    ];
    return {
        list: function() {
            return works;
        },
        selected: function() {
            return works[0]; // maybe selected[]?
        }
    };
});

portApp.controller("listController", ["$scope", "workFactory", 
    function($scope, workFactory) {
        $scope.allWorks = workFactory.list();
    }
]);

portApp.controller("itemController", ["$scope", "workFactory", "$stateParams",
    function($scope, workFactory, $stateParams) {
        var detPath = $stateParams.itemLink;
        //$scope.selectedWork = workFactory.selected(detPath);
    }
]);

Answer №1

Please make sure that the chosen option is a function that takes one parameter:

 return {
   list: function() {
     return works;
   },
   selected: function(detPath) {
     //Filter based on the detPath
     selected = works.filter(function(work) {
       return work.Link == detPath;
     });
     return selected;
   }
 };

After that, you can utilize it in the controller:

 portApp.controller("itemController", ["$scope", "workFactory", "$stateParams",
   function($scope, workFactory, $stateParams) {
     var detPath = $stateParams.itemLink;
     $scope.selectedWork = workFactory.selected(detPath);
   }
 ]);

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

Setting an AngularJS variable as the name attribute in an HTML tag

Important Values {{item.name1}} equals item_name_1 {{item.description}} represents a Band Situation 1 <input name="item_name_1" value={{item.description}}> The input field is filled with Band Situation 2 <input name={{item.name1}} value={{ ...

Searching for a specific string within an array using JavaScript: tips and tricks!

I have a variable which looks like this: var d; d = [{'category': 'Hourly Report','from_start_datetime': '2013','format': 'yyyy-mm-dd hh:ii:ss', 'id': 'dateRangeTo'}] When I ...

issue with deploying a software package and getting it installed

I developed a basic package containing only a simple <div> x </div> and published it using npm publish. When I attempted to install it in a project using npm i, I encountered the following error message: Support for the experimental syntax &apo ...

Creating compressed files using JavaScript

I am currently working on unzipping a file located in the directory "./Data/Engine/modules/xnc.zip" to the destination folder "./Data/Engine/modules/xnc". Once I have completed writing to these files, I will need an easy method to rezip them! While I wou ...

Having trouble retrieving multiple selected values from the paper listbox in Polymer 3

I'm attempting to retrieve multiple selected values in a paper-listbox element in Polymer. <paper-dropdown-menu label="{{_getLabel('Activity Type')}}" id="fromMenu" on-paper-dropdown-close="fromAccountChanged" searchable="true"> ...

Tips for Sending Request Parameters to Angular Application

My Angular app, created with Angular CLI, is hosted on Heroku using express. The setup looks like this: const express = require('express'); const app = express(); // Serve the static files in the dist directory app.use(express.static(__dirname + ...

Introducing a fresh input field that includes a dropdown selection feature

When a user clicks on the "+" button, a new row should be added with a dropdown and input field. I want the input field name to be the dropdown value for each row. If "Facebook" is selected in the first dropdown, it should not appear in the second dropdo ...

Javascript error: Function not defined

For some reason, I seem to be hitting a roadblock with this basic function. It's telling me there's a reference error because apparently "isEven" is undefined: var isEven = function(number) { if (number % 2 == 0) { return true; ...

Custom close functionality for AngularJS lightbox implemented in controller

I'm looking to create a customized close controller that will not only close the lightbox when I click "OK" in the alert, but I am unsure of how to do it. Here is the link for reference: Lightbox ...

Tips for utilizing rest parameters in JavaScript/Typescript: Passing them as individual parameters to subsequent functions, rather than as an array

Question about Typescript/JavaScript. I made my own custom log() function that allows me to toggle logging on and off. Currently, I am using a simple console.log(). Here is the code: log(message: any): void { console.log(message) } Recently, I decid ...

Configuring a module in AngularJS: step-by-step guide

Having just started learning AngularJS, I feel confident with the basics and now seeking to grasp some best practices. However, as I analyze a code snippet, I find myself encountering certain parts that remain unclear to me: ciApp = angular.module("myApp ...

Guide to Wrapping Inner or Wrapping All Elements Except for the Initial Div Class

I am looking to enclose all the elements below "name portlet-title" without including other elements within the "div class name portlet-title". I have attempted the following methods: 1) $("div.item").wrapAll('<div class="portlet-body"></div ...

The Google Maps marker is not accurately displaying the designated location

While working on my project, I successfully integrated Google Maps. However, I have encountered a problem: when I search for a specific location, the marker is not displaying at the correct point, but rather somewhere else. The latitude and longitude value ...

Adjust the height of images to be consistent

I'm currently working on creating a grid layout with 4 images in a row using DaisyUI card component. However, I've run into an issue where there is white space at the bottom of some images due to varying image heights. Is there a solution that wo ...

Navigating between two table components in React JS

I am a beginner in the world of React and I am struggling with switching between these two tables. Despite consulting the documentation for inline conditional statements, I still couldn't figure it out. My goal is to have the tables switch after click ...

The error message is stating that the module located at C://.. does not have an exported member named "firebaseObservable"

Trying to follow an Angular/Firebase tutorial for a class but encountering issues. The FirebaseListObservable is not being imported in my component even though I have followed the tutorial closely. I've looked at similar questions for solutions but ha ...

The data in AngularJS ng-repeat does not appear accurately

I've encountered an unusual issue while working with ng-repeat in combination with ui-router. To test this, I set up a simple markup that fetches data from my local node server and displays it using ng-repeat. During the test, I add a new row to the ...

When $(.class) displays result, Javascript ceases execution

In the code snippet below, I am trying to load a group of products from a category when the user clicks on the .expandproducts button: $('.expandproducts').click(function(){ id = $(this).attr("data-id"); urlajax = document.location.origi ...

Issue with AJAX MVC HTML: jQuery value is not blocking API call

Upon clicking a button, I am triggering a web API call using AJAX. My form is utilizing JqueryVal for form validations based on my viewmodel data annotations. The issue I am facing is that when I click the "Listo" button in my form, it executes the API ca ...

Verify the Ajax submission of a post request prior to transmitting any data

Currently, I am utilizing Google Tag Manager to handle form submission inside a Bootstrap modal. Due to limited backend access, I have opted for GTB to target a specific button and utilize the onClick event. <script> $(document).on('submit&apos ...