angularjs - Give other controllers access to api call data -
what i'm trying is:
- make api call application runs (using
ui-router, idea http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/) - store data 'globally' other controllers can have access data
- once api call done , controllers have resolved, show ui (i don't want flash of loaded content)
i know create angular service make api calls within each controller, if have 2 controllers on page, don't want make 2 of same requests.
in example below, have nav.controller.js needs access mydata.
home.config.js
angular.module('myapp') .config(['$stateprovider', '$urlrouterprovider', function($stateprovider, $urlrouterprovider) { $urlrouterprovider.otherwise('/'); $stateprovider .state('home', { url: '/', templateprovider: function($templatecache) { return $templatecache.get('home.client.view.html'); }, resolve: { myservice: 'myapiservice', mydata: function(myapiservice){ return myservice.get().$promise; } }, controller: 'homectrl home' }); } ]); home.controller.js
angular.module('myapp') .controller('homectrl', ['mydata', function(mydata){ var self = this; // yay works! console.log(mydata); } ]); nav.controller.js
angular.module('mydata') .controller('navctrl', ['$scope', 'mydata', function($scope, mydata) { // boo doesn't work console.log(mydata); } ]); another.controller.js
angular.module('anothermodule') .controller('anotherctrl', ['$scope', 'mydata', function($scope, mydata) { // boo doesn't work console.log(mydata); } ]);
you should still use service. however, service shouldn't make api call - should store data. code like
home.controller.js
angular.module('myapp') .controller('homectrl', ['myservice', function(myservice){ var self = this; // yay works! console.log(myservice.mydata); } ]); nav.controller.js
angular.module('mydata') .controller('navctrl', ['$scope', 'myservice', function($scope, myservice) { // boo doesn't work console.log(myservice.mydata); } ]); another.controller.js
angular.module('anothermodule') .controller('anotherctrl', ['$scope', 'myservice', function($scope, myservice) { // boo doesn't work console.log(myservice.mydata); } ]); and inside myservice.get() function store returned data in mydata
Comments
Post a Comment