angularjs - $rootscope object model from service not (always) available in every controller -
in app definition have:
var myvtmodule = angular.module('vtapp', ['myappdev','mongoapi']); myvtmodule.run(function($rootscope, $location, shop){ $rootscope.shopdata = {}; shop.getshop(function(response){ $rootscope.shopdata = response; }); })
shop service retrieving data server, works. problem in controller don't have access shopdata, empty, working normally.
function supportctrl($rootscope, $scope) { console.log ($rootscope.shopdata); }
why not updating when receives response service? can't put shop.getshop in controller need everywhere...
my suggestion use controller inheritance , service child controllers can have access shop. here demo:
http://beta.plnkr.co/edit/dtjwlmi3jhcdzthejdnn?p=preview
code:
angular.module('myapp', ['myapp.services']); function mainctrl($scope, shopservice) { $scope.shop = shopservice.getshop(); } function childctrl($scope) { } angular.module('myapp.services', []). factory('shopservice', function ($rootscope) { var shop = { storename: 'your store' }; var service = { getshop: function() { return shop; } } return service; });
html sets child controller relationship:
<html ng-app="myapp" > <head> <meta charset="utf-8"> <title>angularjs plunker</title> <link rel="stylesheet" href="style.css"> <script>document.write("<base href=\"" + document.location + "\" />");</script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script> <script src="app.js"></script> </head> <body ng-controller="mainctrl"> store {{shop.storename}} <div ng-controller="childctrl"> store name is: {{shop.storename}} </div> </body> </html>
you notice shop
available child because parent scope retrieved it. set service can make testable/etc. besides inheritance inject shopservice
each controller , have them make call, if have lot of controllers become tedious.
some more info on scope inheritance:
can inherit parent controller's variables? http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller