简体   繁体   中英

Angular.js Services

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.

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.

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)

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");

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM