Exploring the relationship between $resource and controllers

I am currently working on deciphering the code snippets below. From what I gather, there are three resource objects - CategorySrv, ArticleSrv, and SearchSrv that interact with REST server data sources.

app.factory('CategoryService', function($resource) {
    return $resource('categories');
});

app.factory('ArticleService', function($resource) {
    return $resource('articles');
});

app.factory('SearchService', function($resource) {
    return $resource('articles/search');
});

My question is: when does the controller's code execute? It seems like it only runs once when the page loads. When will it run again? As far as I know, the controller's code doesn't run in a loop but is called either when its methods are invoked from the view or when the section of the page associated with this controller is loaded.

When triggered, the listed resource objects are passed as arguments and the controller's function is executed:

app.controller('AppCtrl', function($scope, $location, CategoryService, ArticleService, CartService) {


CategoryService.query(function(response) {
    $scope.categories = response;
});

ArticleService.query(function(response) {
    $scope.articles = response;
});

CartService.get(function(response) {
    $scope.cartInfo = response;
});

Am I interpreting this correctly? And could you explain the difference between using get and query in the above context?

Answer №1

Absolutely. The code will only execute once, when the controller is loaded.

When using $resource, you have the choice between utilizing get or query. The main difference lies in that query will immediately return an empty array or object based on whether isArray is set to true. This feature helps prevent errors from occurring during rendering, avoiding situations where Angular anticipates an array or object but receives undefined (as in cases of asynchronous actions). Upon receiving a response with data, the digest cycle will trigger as changes in $scope are detected, subsequently refreshing your view.

For more information, refer to the documentation: https://docs.angularjs.org/api/ngResource/service/

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

Encountering error while attempting POST request in POSTMAN - "Unable to modify in restricted editor."

I'm facing a bit of a dilemma here. I can't seem to figure out how to make my editor in Postman stop being read-only. Can anyone lend a hand? Whenever I try to send a Post Request, my editor just won't cooperate and stays in Read-Only mode. ...

Vue: Struggling to render JavaScript Map containing keys and values using v-for :key

I have an example Json data like so: { "data":{ "1":{ "color":"red", "size":"big" }, "2":{ "color":"red", "size":"big" }, "3":{ "color":"red", "size":"big" }, ...

What is the process for converting the output of cryptoJS.sha256 to binary in a Postman pre-request script?

Seeking assistance in creating an HMAC signature using a pre-request script in Postman. While troubleshooting, it has become apparent that there is an issue with the signature generation process. Although a proof of concept example provides expected result ...

How can I enhance data from an AJAX callback in Mapbox with an additional layer?

With the code snippet below, I am aiming to utilize event data from an API to create a mapbox layer. This layer will be used to place markers and symbols on the map. However, I prefer not to use Mapbox markers as they cause issues with my code. I have suc ...

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

Uploading documents using AngularJS and Express.js

I'm currently working on a project that involves uploading files using AngularJS and Node.js (with Express.js). To facilitate this process, I am utilizing danialfarid/angular-file-upload. Within my view (built with jade), the code snippet below showca ...

NodeJS server connection delay

My server has an Express NodeJS instance installed. The API stops responding when it is overloaded, leading to the following response: POST /my/api/result - - ms - - I attempted the following in ./bin/www: server.on('connection', function(sock ...

Is there a way to create a discord.js bot that can search for past messages without the need for a json file or storing them in a database?

Similar to the search feature in Discord. Imagine being able to enter !search [user] [query] and getting a response like "50 messages match your query." This would be like a word counting bot that doesn't need a database or local storage.The bot ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

Create a table by incorporating the information from the page along with additional content

I need to extract the data from a list and convert it into a table, add some additional content that I will provide, and then align the table accordingly. While I can easily align elements and already have the list, I am facing difficulty in converting it ...

Encountering issues importing Ace Document Object in a Vue webpack project?

In my Vue and Webpack project, I am trying to incorporate the Ace editor. My goal is to associate each file with a single instance of an Ace Document. To achieve this, I followed the default import method: import Ace from 'ace-builds' When atte ...

Unable to open modal using a button in PHP

<?php $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_array($result)) { echo '<tr><td>'; echo '<h5 style="margin-left:6px; color:black;">' . $row['id'] . '</h5> ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

Tips on retrieving an object in a JavaScript function through an HTML event

The js function code is as follows: //Assigning the index of theater array to a variable $scope.setTheaterValue = function(name) { var index = $scope.path.map(function(s){return s.name}).indexOf(name); $scope.path = $scope.path[index]. ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

angularjs select not chosen option

Hey there, I'm currently attempting to select an item from an array in the select options by using a string value. Below is my HTML code: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularj ...

Navigating through various JavaScript libraries with varying loading times can be a tricky task when working within the Angular

As I dive into learning Angular, I find myself pondering the architecture of my app. The project I'm embarking on will heavily rely on various external libraries such as jQuery, jQuery.ui, jsPlumb, and more, each with their own loading times. I unde ...