Angular.js Services

This was solved with a service and not a factory as described in the plunker: http://plnkr.co/edit/uh23lrXz2mI4ukvJvxws?p=preview provided by @Incognos. The accepted answer was @Tomislav as he first mentioned using the service.

I created a controller to handle store items, they are stored as such (remote repeats to save space 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 store this data so that it can be retrieved from another view / controller. (This will be the last page of the cart.) I tried using .factory then in controller $ scope.products = serviceName.items; but to no avail. I have added this service through the controller as well. I am given an injector error: modulerr.

To clarify, the service created is

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

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

      

The controller is then like this:

'use strict';

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

      

I got stuck on how to put my data from the original controller into a service and then inject the service into the controller to render the items again. To mark, NOT using the service, the data is displayed in the view perfectly.

+3


source to share


4 answers


Don't use a factory, create a service that is always single and will store 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 into the controller:



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

  var item={qty:0}

  StoreService.save(item);

  $scope.product=StoreService.get();

  console.log($scope.product);

});

      

Since the service is singleton, it is global in the whole application. You can enter it into any controller and it will remember your saved values.

+3


source


Application 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 display multi-file)

+1


source


Try it,

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

      

but make sure your application is initialized only once.

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

      

this line, subsequently, should be,

angular.module("angularStoreApp");

      

0


source


Just make a direct link to the collection item

residing in the service inside each of the consuming controllers and manipulate the link directly.

In the following example, this template and two controllers 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>
      

Run codeHide result


0


source







All Articles