1

I have a service which I would like to use across multiple controllers. The services is defined like this:

app.factory('Data', ['$http',
  function($http) {

    var Data = this;
    var theProduct = {};

    return {
      product: function() {
        return theProduct;
      },

      getProduct: function(ext_id) {

        return $http.post('get_product', {
          product_id: ext_id
        }).success(function(data) {
          theProduct = data;
        });

      }
    }
  }
]);

I have a form, that uses the ProductFormController to retrieve product data when it's submitted. That controller looks like this:

app.controller('ProductFormController', ['$scope', '$http', 'Data',
  function($scope, $http, Data) {

    /*
     * Get a product and all of it's data from the server
     */
    $scope.getProduct = function() {

      Data.getProduct($scope.extProductId).success(function(data) {
        console.log(data);
      });
    }

  }
]);

Then, I have an AppController, which should display certain sections when a product object exists in the Data service.

<div class="row" id="productInfo" ng-show="product().id" ng-controller="AppController">/div>

Within AppController, I have this line:

$scope.product = Data.product;

I would like the productInfo div to show whenever a product object exists in the Data service, but it seems that the variable never gets updated. I've seen this question, but do not believe the accepted answer actually answers the question:

Angular: share asynchronous service data between controllers

4
  • Where is ProductFormController being used? What if the data has not been fetched yet by the time appcontroller runs? Commented Oct 3, 2014 at 15:55
  • The data has not been fetched yet, but I thought that since I am binding to a function product().id, that when the data is fetched, the view will update. ProductFormController is at the top of the page and contains a form to enter a product ID, followed by the AppController, which contains the rest of the app and should display results based on the product that is fetched above. Commented Oct 3, 2014 at 16:01
  • Yes it will update.. But there might be some issue in the portion of code that you are not showing us.. plnkr.co/edit/Hbu2J4dfKMtAcu8Mvt2Y?p=preview Check if your data actually is being fetched or not also check data's structure, if it is what you expect. Commented Oct 3, 2014 at 16:01
  • You're right it does update. And you're there was an unrelated code issue that I mistook for this issue. Thanks for making me take a second look. Commented Oct 3, 2014 at 16:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.