Using optional arguments in my AngularJS controller.js

In my controller.js file for AngularJS, I have the following code snippet:

app.controller('MetaDetailGroupList', ['$scope', '$http', function($scope, $http) {
        $http.get(Routing.generate('meta-detail-group-list')).success(function(data) {
            $scope.MetaDetailGroup = data;
            $scope.orderProp = 'name';
            $scope.currPage = 0;
            $scope.pageSize = 10;

            $scope.totalMetaDetailGroup = function() {
                return Math.ceil($scope.MetaDetailGroup.entities.length / $scope.pageSize);
            };

        }).error(function(data, status, headers, config) {
            $scope.MetaDetailGroup.message = "An error occurred while processing the data, please try again.";
        });
    }]);

This function is used to create a list of items and it functions as expected. Some of these items have a parent >> children relationship, requiring another call to the same function but with an ID passed as an optional parameter. The only change necessary is in this line:

From: $http.get(Routing.generate('meta-detail-group-list')).success(function(data)

To: $http.get(Routing.generate('meta-detail-group-list' + '/'+id)).success(function(data) 

Is there a way to achieve this without creating a separate function specifically for this purpose?

Answer №1

To improve the efficiency of your code, I recommend moving the $http call to a separate service where you can handle the id processing logic. Here's an example implementation:

app.service('MetaDetailGroupListService',function($http) {
    return {
        metaDetailGroupList : function(_id) {
            var _s = (typeof _id === 'undefined') ?
                'meta-detail-group-list' :
                'meta-detail-group-list' + '/' + _id;
            return $http.get(Routing.generate(_s));
        }
    }
});

app.controller('MetaDetailGroupList', ['$scope', 'MetaDetailGroupListService',
function($scope, MetaDetailGroupListService) {
    MetaDetailGroupListService.metaDetailGroupList(id).success(function(data) {
        $scope.MetaDetailGroup = data;
        $scope.orderProp = 'name';
        $scope.currPage = 0;
        $scope.pageSize = 10;

        $scope.totalMetaDetailGroup = function() {
            return Math.ceil($scope.MetaDetailGroup.entities.length / $scope.pageSize);
        };

    }).error(function(data, status, headers, config) {
        $scope.MetaDetailGroup.message = "An error occurred while processing the data, please try again.";
    });
}]);

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 seems to be the problem at hand, and where exactly is the issue located?

import React from 'react'; const card = ({name, email, id}) => { return( <div className='tc bg-light-green dib br3 ma2 grow bw2 shadow-5'> <img alt="robots" src = {'https://uniqueimage. ...

Get the color at a specific index in a JavaScript array

When I click a button, a pie chart is generated using chartjs. The results are displayed based on the filters applied, showing (Name | Value%): Service_1 | 10 Service_2 | 15 Service_3 | 75 Sometimes, certain results may not appear: Service_1 | 20 S ...

The $broadcast method in AngularJS allows us to send messages to

Is it possible to determine the outcome of $broadcast in AngularJS - whether it was successful or not? $rootScope.$broadcast($scope.abc + ':' + type + 'question', { abcSlug: $scope.abcSlug, questionSlug: questionSlug, abcOb ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

What is the best way to adjust the height of an IFrame to match the size of its content?

I attempted to set the height of an IFrame to 100% (similar to setting a <div> to height:auto). I specified the height attribute in the <iframe> tag as 100% and also set the height in the style to 100%, but it doesn't appear to be functio ...

Expanding Vue JS Vuetify Panels in a V-for Loop to Reveal Multiple Panels

When pulling data from a database and looping through it in the DOM using a "v-for" loop, I encountered an issue with Vuetify expansion panel components. The problem is that when a user clicks to open one expansion panel, it ends up opening all other panel ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

Navigate using jquery on a keyboard starting from a designated input text field

I'm currently developing an internal web application and I want to incorporate keyboard navigation into it. After doing some research, it looks like using JavaScript is the most effective way to achieve this. Below is a snippet of what I have come up ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

The organizational structure of data in MongoDB for posts, comments, saved content, and likes

I am currently diving into the world of MEANJS web development and working on structuring my data. As a newcomer to the NoSql concept, I am seeking guidance on the best practices to follow. The data I need to store includes: questions answers likes saved ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

Experiencing delays when loading more than 200 input fields on the screen due to

So I've been working on a project that involves having potentially unlimited input fields. However, once I add around 200 items, the performance starts to degrade significantly. You can see a demo of this issue here: (To test: Focus on the last input ...

Error: The function is not defined on this.props during the handleCHange event

After going through numerous answers to similar questions on this topic, I believe that I am following all the necessary steps but for some reason, it is not working. Below is the specific section of code that is causing the error: import React from &apos ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

What is the correct syntax for utilizing a variable in inline styles within ReactJS, specifically when working with the --i:0

            The question has been raised previously, but unfortunately, it was left unanswered in this thread. The variables play a crucial role in this piece of code as they are intended to be utilized in various CSS functions for animating them wi ...

How can I dynamically unload a JavaScript file that was previously loaded with RequireJS? Alternatively, how can I handle exclusive dependencies or reset RequireJS?

I'm facing a dilemma with two JavaScript files that cannot be loaded simultaneously. One needs to be unloaded before the other can be loaded when a specific button is clicked. Here's an outline of my current approach: //pseudocode if user click ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

Configure WebStorm so that node_modules is set as the library root, while simultaneously excluding it from indexing

Can WebStorm projects be configured to set the node_modules as the library root, while also excluding it from indexing? I thought I saw a project that had node_modules marked as both library root and excluded, but I'm unsure how to do this. Does anyo ...