Reputation: 6025
I want to access a variable from my controller so I can use it in my service! I thought that if I made the variable global I could access it in my service, but it's not working out hehe. The variable is shops btw!
Here is where I'm creating the variable:
$scope.$on('$ionicView.enter', function (e) {
ecommercer.getData().then(function (s) {
$scope.shops = s.vendors
$scope.categories = s.categories
$ionicScrollDelegate.resize()
if ($stateParams.id && $stateParams.id.length > 1) {
$ionicTabsDelegate.showBar(false)
ecommercer.saveShopById($stateParams.id)
$state.go('tab.ecommerce.shop')
}
})
})
Here (the same file) is where I'm using my variable:
$scope.$watch('selectedCategory.name', function (newval, oldval) {
if ($scope.selectedCategory.name != undefined) {
$scope.shops = ecommercer.filterByCategory(newval.id)
} else {
$scope.shops = ecommercer.filterByCategory(null)
}
})
Here is where I create the same variable in my service file:
app.service('ecommercer', function (eapi, $q, storage, $http, endpointHandler, $state, $rootScope, $filter) {
var products, categories, vendors, shops
Finally, here is when I'm trying to use it in my service:
function filterByCategory(categoryid, shops) {
if (!categoryid) return shops
console.log(shops);
var newlist = []
for (var s in shops) {
if (shops[s].category.split(',').length > 0) {
for (var c in shops[s].category.split(',')) {
if (shops[s].category.split(',')[c] == categoryid) {
newlist.push(shops[s])
}
}
}
}
return newlist
}
Upvotes: 0
Views: 235
Reputation: 3820
Your controller is actually just the glue between your view and singleton services... They are (re)created and detroyed throughout your applications lifecycle - services are created once (singletons - and reused after creation when injected).
Therefor you should turn your approach around, instead of holding your variable you want to share accross your application (controller / service) inside your controller - on the $scope
object - you should create it inside your singleton service ecommercer
.
Through the getter / setter principle you can update / retrieve the variable shops
inside your singleton service ecommercer
.
See following rough example to illustrate on how you should change your approach.
CONTROLLER & SERVICE
angular
.module('app', [])
.controller('MainController', MainController)
.service('ecommercer', ecommercer)
function ecommercer() {
var shops;
return {
setShops: setShops,
getShops: getShops
}
function setShops(shops) {
this.shops = shops;
}
function getShops(shops) {
return this.shops;
}
}
function MainController(ecommercer) {
var vm = this;
this.setShops = setShops;
function setShops() {
ecommercer.setShops([{
id: 1,
name: 'test shop 1'
}, {
id: 2,
name: 'test shop 2'
}]);
vm.shops = ecommercer.getShops();
}
}
VIEW
<div ng-app="app" ng-controller="MainController as vm">
<div ng-click="vm.setShops()">
Set shops
</div>
<div>
{{vm.shops}}
</div>
</div>
https://jsfiddle.net/DaanDeSmedt/j5uqaxgy/
Upvotes: 1