3

This was solved via using a service rather than a factory as described on the plunker: http://plnkr.co/edit/uh23lrXz2mI4ukvJvxws?p=preview provided by @Incognos. Accepted answer was @Tomislav as he first mentioned using a service.

I've created a controller to handle the stores items, they're stored like such (removed reiterations to save space on here):

'use strict';

angular.module('angularStoreApp')
  .controller('storeCtrl', function($scope){
    $scope.product = {
      items: [
        {
          qty: 0,
          stock: 5,
          price: 99.00,
          name: 'Almond Toe Court Shoes, Patent Black',
          category: 'Womens Footerwear'
        }
      ]
    };
  });

I need to create a service to hold this data so it can be accessed from another view/controller. (It'll be the final cart page). I've attempted to use .factory, then in the controller $scope.products = serviceName.items; but to no avail. I've injected the service via the controller also. I'm given a $injector:modulerr error.

To clarify, the service I created is this

var app = angular.module("angularStoreApp", []);

app.factory("StoreService", function() {
  var products = {
    items: [
      {
        qty: 0
      }
    ]
  };
  return products;
});

The controller then is as such:

'use strict';

angular.module('angularStoreApp')
      .controller('storeCtrl', function($scope, StoreService){
    $scope.product = StoreService.items;
  });

I'm stuck on how to put my data from the original controller into the service and then inject the service into the controller to display the items once again. To note, NOT using a service, the data is displayed in the view perfectly fine.

4 Answers 4

3

Do not use factory, create a service which is always singleton and will hold your data:

var app = angular.module('angularStoreApp',[]);

app.service('StoreService',function(){

  var products={
    items:[]
  };

  this.save=function(item){
    products.items.push(item);
  };

  this.get=function(){

    return products;

  };
});

Inject it in your controller:

app.controller('storeCtrl',function($scope,StoreService){

  var item={qty:0}

  StoreService.save(item);

  $scope.product=StoreService.get();

  console.log($scope.product);

});

Because service is singleton it is kind of global in whole application. You can inject it in any controller and it will remember your saved values.

Sign up to request clarification or add additional context in comments.

6 Comments

To expand on this. Services are new'd, and the same instance is then kept. Factories just return the function as it is each time, so you can call new on it yourself if you want.
@Tomislav, thanks for this. Though, to be clear, I need the data e.g qty to be stored so I can use this in another view later, for example, the cart. I can see the data is being stored in the controller? Correct me if I'm wrong, I'm new to angular.
It is stored during whole wab page life cycle, not in the controller but in the service. You can inject that service later in any other controller
Hey, I've used the above code, but it's not working and saying app is not defined. Any ideas?
add this first: var app = angular.module('angularStoreApp',[]); I edited my answer above.
|
1

App from top to bottom using a Service:

// main.js
var app = angular.module('app', [])
.controller('buyerCtrl', function($scope, StoreService) {
  $scope.items = StoreService.items();
  $scope.buyMe = function(item) {
    StoreService.add(item);
  };
})

.service("StoreService", function() {
  var products = [];
  var items = [{
    qty: 0,
    stock: 5,
    price: 99.00,
    name: 'Almond Toe Court Shoes, Patent Black',
    category: 'Womens Footerwear'
  }, {
    qty: 0,
    stock: 5,
    price: 99.00,
    name: 'Black Lace Shoes, Patent Black',
    category: 'Mens Footerwear'
  }];
  this.items = function() {
    return items;
  };
  this.add = function(product) {
    products.push(product);
  };
  this.count = function() {
    return products.length;
  };
  this.cart = function() {
    return products;
  };
})

.controller('cartCtrl', function($scope, StoreService) {
  $scope.cart = StoreService.cart();
  $scope.cartCount = StoreService.count();
});

see Plunkr (plunker updated to show multi-file)

9 Comments

Hey, thanks for that, I've added that code to my controller, but it's not allowing anything within the store view to be loaded, that, or any other view. Also, var products is still being thrown as a redundant variable.
I edited and converted the factory to a service, as mentioned by @tomislav - you will need to post the additional code so that I can help any further.
would have been handy to have the HTML in the future as well... but I included a plunkr with a working "cart"
as long as you define it in the same module name 'angularStoreApp', otherwise, you will have to inject that module into the app
If it works, please select @tomislav as the correct answer since he brought up the right answer to your question first
|
0

Try this,

angular.module('angularStoreApp')
      .controller('storeCtrl', function($scope, StoreService){
        $scope.product = StoreService;
      });

but make sure, your app is initialised only once.

var app = angular.module("angularStoreApp", []);

this line, afterwards, should be,

angular.module("angularStoreApp");

2 Comments

Hey, Z.a, I've done the first. I assume you want me to add var app = angular.module("angularStoreApp", []); into the controller? It's already being initialised only once in the services file. To note, they are in seperate files within the same child directory. So services.js and StoreCtrl.js are within the same directory of "store"..
doesnt matter where it's really. u should use this line once, and preferably before anything else, angular.module("angularStoreApp", []); never use it with brackets again. u can do this to create controllers, services, etc angular.module("angularStoreApp").controller, factory, etc
0

Simply make a direct reference to the service's exposed item collection inside each one of the consuming controllers, and manipulate the reference directly.

The following example uses this pattern and two controllers to demonstrate the behavior:

var module = angular.module('myapp', []);
 
module.service('StoreService', function(){
 this.items = 
   [
        {
          qty: 0,
          stock: 5,
          price: 99.00,
          name: 'Almond Toe Court Shoes, Patent Black',
          category: 'Womens Footerwear'
        }
      ] 
   ;
});
         
      
module.controller('element1Controller', function($scope, StoreService){
  $scope.items = StoreService.items;
  
  $scope.add = function(){
    
    $scope.items.push({
          qty: 2,
          stock: 10,
          price: 9.00,
          name: 'Random Item',
          category: 'Womens Footerwear'
        });
              

}
});

module.controller('element2Controller', function($scope, StoreService){
  $scope.items = StoreService.items;
});
<html ng-app='myapp'>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-controller="element1Controller">
  Controller 1<br />
  {{items}}
  <br />
  <button ng-click='add()'>Add Item to Cart</button>
  
</div>

  <br />

  <div ng-controller="element1Controller">
  Controller 2<br />
  {{items}}
</div>
</html>

Comments

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.