What is the mechanism behind Angular or JS retrieving data without the need for defining a parameter name?

The title of this question may not fully capture what I am trying to ask. To provide more clarity, consider the following example:

.service('Book', function($http) {
   var bookService = {};
   Service.getBook = function() {
      return $http.get('/api/book');
   }
})


.controller('BookController', function(book) {

var vm = this;

Book.getBook()
    .success(function(data) {

    })
})

How does the getBook() function return data into the 'data' object?

Answer №1

Do you have a question about how javascript replaces written code with logical objects at runtime?

For example:

console.log(new Array({"getWalkDetails":function(){return {"MaxSpeed":15, "DistanceWalked": 123}} },
                       "walking on sunshine", 
                       "oh oh" ).shift().getWalkDetails().MaxSpeed);
//outputs "15" to the console

This can be rephrased as:

var arr = new Array();
var func = function(){
        var details = new Object();
        details.MaxSpeed =15;
        details.DistanceWalked = 124;
        return details;
}
var obj = {"getWalkDetails" : func};
arr.push(obj);
arr.push("walking on sunshine");
arr.push("oh oh");

var firstItem = arr.shift();
//the array function 'shift()' is used to remove the first item in the array and return it to the variable
var walkingDetails = firstItem.getWalkingDetails()//same as func() or obj.getWalkingDetails()
console.log(walkingDetails.MaxSpeed);//15

We store most of the interpreted outputs as variables for separate use.

EDIT: If you are wondering how to pass objects by reference in javascript to allow the mydata variable to receive any changes made to it in the function it is passed to, the following question may be helpful: javascript pass object as reference

EDIT: I have made some additional edits to the code above

Answer №2

I'm a little unsure of what you're trying to convey, especially since I don't have experience working with Angular. However, it seems like you might be intrigued by this clever code snippet:

//+ fn -> [a]
var getParameterNames = (function () {
    var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
        ARGUMENT_NAMES = /([^\s,]+)/g;

    return function (fn) {
        var fnStr = fn.toString().replace(STRIP_COMMENTS, ''),
            names = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);

        return names || [];
    };
})();

function add (x, y) {
    return x + y;
}

console.log(getParameterNames(add));    // => ['x', 'y']

Update: Also, you can find a jsfiddle link 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

What could be causing my code to fail in the useEffect hook every time I make updates to my JSON

I have a function that receives JSON data from the server. Using the {jsonData.map((element) => renderComponents(element, jsonData))} function, I loop through the data and send each object to the renderComponents function along with the full JSON data. ...

Unable to set DIV to 'inline-block' or none based on checkbox selection

Despite reviewing multiple examples, I am still struggling to make this DIV visible and hidden by clicking a checkbox. Can someone please review my JavaScript code? <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Conten ...

How to Restrict the Use of Conditional "If" Statements in Another Function in Angular 7

How can I use an IF condition inside a function to only execute once for a specific action and not for another action? I have a function that is called twice, but I want the first "IF" condition inside the function to only be triggered when the add bank b ...

The troubleshooting of debugging javascript remotely on IntelliJ with the JetBrains Chrome extension is proving to be unsuccessful

I've been attempting to set up a debugger for some JavaScript files that I'm working on in IntelliJ (version 2020.1.4). Following the guidelines provided here Debug with JetBrains Chrome extension, I believe I have successfully completed all the ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

Is it necessary to exclude the 'scripts' folder from your Aurelia project's .gitignore file?

Should I exclude the 'scripts' directory that Aurelia is building to in my CLI project from Git by adding it to .gitignore, or is there a specific purpose for tracking changes to this directory? ...

Variations in speed with closely related jQuery expressions in Internet Explorer

When running in Internet Explorer, test the performance of executing an expression like: $('div.gallery div.product a"); against a similar expression: $('div.gallery').find("div.product").find("a"); It has been found that sometimes the s ...

The styles in the published npm package are not being applied

Currently in the process of developing a custom npm package named react-clear-carousel, which is essentially a React component with enhanced styles using SCSS. Although I have implemented class names, the styles are not being applied when testing it out. ...

Issue encountered with the latest version of Selenium web driver when using Firefox browser

I am currently using Selenium jar version 3.3.1 with Firefox 43.0.4 and Eclipse Mars.2 Release (4.5.2). When I execute the following code: import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selen ...

Running a JS/JSON function in Snowflake that results in a syntax error

Can anyone help me troubleshoot the issue with the following function? I am receiving this error message: SQL compilation error: syntax error line 1 at position 0 unexpected 'function'. Should I be using JSON Script or Javascript for this? func ...

Implement a feature in Vuejs where the user can easily move to the next field by simply

I need help implementing a feature that moves the focus to the next field when the enter key is pressed. I've tried the following code, but it's not working as expected. When I added a debugger in the focusNext method inputs[index + 1].focus();, ...

The child directive has the ability to interact with every parent directive

I am attempting to create a slider using angularJS. Within this slider, I have implemented a child directive with event listeners. Whenever the main event (mousedown) is triggered, it invokes a function from the parent directive through a controller and up ...

Refreshing a component using a sibling component in React

Currently, I am delving into the realm of React and embarking on a journey to create a ToDo App. However, I've hit a snag while attempting to add a new task to the list. Despite successfully adding an item to the list upon clicking the add button, upd ...

What could be the reason for my Bootstrap popover malfunctioning?

I've been attempting to incorporate the Bootstrap popover into my project. I copied the code exactly from the example provided on the website, but unfortunately, it doesn't seem to be functioning properly on my site. Below is the full code snippe ...

Clearing Arrays in React Native Using useState

I'm struggling with the following code which aims to create an animated polyline for a map. I came across some examples online, but they were using outdated methods and didn't include useEffect or useState. I can't seem to clear the polylin ...

Using React Native to Store Items in Flatlist via AsyncStorage

My challenge involves displaying/storing a list of items in a flatlist. The issue arises when I save an item and then load it on another screen; there seems to be a repetitive pattern (refer to the screenshot). Additionally, adding a new item results in re ...

After successful login, the user will be automatically directed to the next page with

I am encountering challenges with a specific portion of my code. I am in the process of sending user information to the server, receiving a token from the user, and then aiming to redirect the user to a URL. However, despite the code entering the if stat ...

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

Having trouble connecting Nextjs with ChromaDB?

I am encountering issues while trying to establish a connection with the Chromadb vector database in Nextjs. The objective is to store user-generated content in Chromadb. Below is the code snippet I am utilizing along with its dependencies: Dependencies V ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...