"Unlocking the power of services in Angular: A comprehensive guide for my

I need to store HTTP request data in one controller and access it from multiple controllers. Here is an example:

My services

angular.module('myApp').service('testService', ['Product','$q',
    function(Product, $q) {
        var products, targetProduct;
        var deferred = $q.defer();

        Product.query({
            Id: 123
            }, function(products) {
                targetProduct = products[0];
                deferred.resolve(products);
        })

        var getTargetProduct = function() {
            var deferredtwo = $q.defer();

            // return deferredtwo.promise;
            deferred.promise.then(function(){
                deferredtwo.resolve(targetProduct);
            })
            return deferredtwo.promise;
        }

        var setTargetProduct = function(targetProduct) {
                targetProduct = targetProduct
        }

        return {
            setTargetProduct: setTargetProduct,
            getTargetProduct: getTargetProduct,
            productPromise : deferred.promise
        };
    }
]);

nav controller

  testService.productPromise.then(function(products){
            $scope.products= products;
             $scope.targetProduct = products[0];
   })
  //when user click the project  ng-click = setTargetProduct(product);
  $scope.setTargetProduct = function(targetProduct) {
         testService.setTargetProduct(targetProduct)
   }

product detail controller

      testService.getTargetProduct().then(function(targetProduct) {
           // works when page first loads
           // but I don't know how to update the targetProduct when user select different             
           //targetProduct which means they trigger setTargetProduct() method
           $scope.targetProduct = targetProduct; 
      })

I am looking for a way to update the targetProduct in the product detail controller when the user selects another targetProduct. Can someone assist me with this? Thank you!

Answer №1

Instead of using unnecessary promises in the function getTargetProduct, you can simplify it by just returning a promise wrapping your local data targetProduct:

var getTargetProduct = function() {
    return $q.when(targetProduct);
}

Note: For simplicity, I will refer to the service testService as productService, and the controller navController as ProductController

The NavController controller retrieves products like this :

productService.getProducts().then(function(products) {
    $scope.products = products;
}

When setting a target product (no changes):

$scope.setTargetProduct = function(targetProduct) {
   testService.setTargetProduct(targetProduct)
}

Solution 1: nested controllers

If ProductDetailController is nested within ProductController, the data targetProduct is shared without additional logic.

Solution 2: independent controllers

If the controllers are not related, you can use $broadcast to send an updateTargetProduct event, and $on to handle it.

In the controller where the target product is set:

$rootScope.$broadcast('updateTargetProduct', targetProduct);  

And in ProductDetailController, listen for this event:

$scope.$on('updateTargetProduct', function(event, data) {
    // manipulate received data
}

Answer №2

Perhaps your circumstances differ from mine, but I created a custom $http service for my needs

var myService = angular.module('apix',[]);

myService.service('api',function( $http ){

        this.http = function( method , path , data ){

            return $http({
                method: method,
                url: path,
                headers: {                          
                    'Content-Type' :  'application/x-www-form-urlencoded'
                },
                data : jQuery.param(data)
            });
        }

});

and then used it like this:

 api.http('POST','your_path', data).success(function(result){ });

Answer №3

angular.module('myApp', [])

.factory('ipFactory', ['$http',
  function($http) {
    var service = {
      getIp: function() {
        return $http.get('http://ip.jsontest.com/', {
            cache: true
          })
          .then(function(data) {
            return data.data.ip;
          });
      }
    }

    return service;
  }
])

.controller('ControllerOne', ['$scope', 'ipFactory',
  function($scope, ipFactory) {
    ipFactory.getIp()
      .then(function(ip) {
        $scope.ipAddress = ip;
      });
  }
])

.controller('ControllerTwo', ['$scope', 'ipFactory',
  function($scope, ipFactory) {
    ipFactory.getIp()
      .then(function(ip) {
        $scope.ipAddress = ip;
      });
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
  <div ng-controller="ControllerOne">
    {{ipAddress}}
  </div>
  <div ng-controller="ControllerTwo">
    {{ipAddress}}
  </div>
</body>

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

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

https://i.sstatic.net/jp2VF.png I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect f ...

Determine whether the current time exceeds a certain time of day

While this may have been asked before, I am struggling to find an answer. How can I determine if the current time is after 17:30 each day? In my scenario, I need to check if it is past 17:30 on Monday to Friday, and if it is Saturday, I need to check if i ...

Using a JavaScript loop with a condition that results in zero

I have a JSON data structure that looks like this: [{20181:{jum:27}},{20182:{jum:27}},{20191:{jum:27}},{20192:{jum:27}},{20201:{jum:27}},{20202}] Attempting to retrieve and display the data using a for loop, here is an example of the code used: let i = 0; ...

Rendering and sending with Node.js simultaneously

Is there a way to render Jade and send additional code after the render without replacing the existing Jade code? Here is an example: var express = require('express'); var router = express.Router(); router.get('/user', function(req, r ...

Conceal a div using jQuery when clicked

I am facing an issue with my script where I need to make a div close only after clicking on a link, instead of anywhere outside the div. http://jsfiddle.net/N4pbP/ $(function() { $('#hidden').hide().click(function(e) { e.stopPropagation() ...

Is there a way to display a button and text upon hovering over an image without using JQuery?

On my current WordPress project, I am faced with the task of creating a gallery that displays text and a button when users hover over an image. I have attempted to use a:hover but have only been able to make limited modifications. Can anyone provide guid ...

Dynamic Component Interactions in VueJS using Mouse Events

Just starting out with Vue and other frameworks, so my approach may not be very "Vue-like". I am attempting to create a versatile button component that can have different behaviors based on a prop, in order to maintain just one button component. The desir ...

Encountered an issue loading a resource due to a lost network connection while using Safari 9 and JBoss WildFly 8.2

After successfully deploying my War file to the JBoss Wildfly 8.2 server, I attempted to access the application link from a remote MAC machine. The application opened correctly, but some functionalities were not working properly. An error message popped u ...

Error message: The 'event' variable is not defined in the Firebase function

I am in the process of creating an appointment application which includes a notification feature. I have integrated Firebase functions to send notifications to users when a new appointment is booked or canceled. However, I encountered an error that says Re ...

What is the reason for elements such as "if" and "else" not being visually

I am currently developing a browser-based code editor with a unique feature. Task: The objective is to highlight specific keywords like if, else, for... when they are entered into the editor. textarea.addEventListener("input", function() { ...

PointerLockControls maintains a constant speed without slowing down (threejs)

I have integrated THREE.PointerLockControls into my project following the implementation demonstrated in this example (view code). The code seems to be accurately translated from the example, but I am facing issues with deceleration of the controller once ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Implementing a Typescript directive in AngularJS to create a class

After using AngularJS for quite some time, I decided to explore Typescript. I managed to convert most of my Angular code to Typescript and found it beneficial, especially when working with services. However, I am struggling to convert the following direc ...

Utilizing React Hook to fetch initial data in useEffect

Encountered a roadblock while attempting to update a hook when the web socket is triggered with new data. I noticed that the hooks are returning the default values I initialized them with inside my useEffect, whereas during rendering it shows the correct v ...

What are the steps to adjust my table width without allowing horizontal scrolling?

1- I need help fixing the width of my table so that it stays within the screen. 2- Is there a way to display only the first 100 characters of table data and show the rest when clicked? Any assistance would be greatly appreciated. Here is a snippet from ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Ensure that the Observable is properly declared for the item list

.html // based on the error message, the issue seems to be in the HTML code <ion-card *ngFor="let invitedEvent of invitedEvents"> <ion-card-content> <img [src]="eventPhotoUrl$[invitedEvent.id] | async"> </ion ...

Even when providing the correct file path for TypeScript in the import statement, TypeScript [TS] is still unable to locate the modules

issue in event-component.ts EventService is declared as an Injectable service class, but I am encountering an error stating [ts] cannot find module '/shared/event.service'. Oddly enough, in app.module.ts, where I have provided the same path fo ...

Padding the body of a single-page Angular application to ensure proper spacing and

How do I add padding to the body of a template in an angular ng-app? Where is the best place to include CSS for a ng-app rendered template? please refer to this fiddle for an example https://jsfiddle.net/aghsqnpa/ div.ngview { padding: 25px 50px 75p ...

An effective method for retrieving elements from a one-dimensional array using nested loops

I have a vector containing data that needs to be stored in the following order: cAge[0] = 'Age (1) (1)'; cAge[1] = 'Age (1) (2)'; cAge[2] = 'Age (1) (3)'; cAge[3] = 'Age (2) (1)'; cAge[4] = 'Age (2) (2)&apo ...