I am very inexperienced with angularjs. I am trying to implement a service to access data across controllers. I used this example.
Below is my js. I haven't posted my HTML because I am just trying to get the logic working within the js first.
angular.module('App')
.factory('TestService', function() {
return {testVar : '22222'}
})
.controller('MainCtrl', function (TestService) {
console.log(TestService.testVar);
}
.controller('SecCtrl', function (TestService) {
console.log(TestService.testVar);
}
This works fine. I console log '22222' each time I access both controllers. I can update the var and it is updated fine between controllers. If I replace return {testVar : '22222'}
with
return {
testVar : { x : '22222' }
}
Then I get the object x : '2222'
logged to console. Which again seems fine.
The thing is I can't really understand the usage of TestService.testVar
in the console log. At first glance I thought it was logging the var testVar from service TestService. From looking at the example however, it is apparent that testVar in this case is actually a key and what is returned is the key value.
Is this the only way to return something from a service, as the key value?
I wish to use the service to access multiple values/objects etc within the service but the use of return in the example only returns the one variable obviously; unless I use if statements, but that seems a little over the top and like I'm really missing something with the use of controllers...
Something like;
angular.module('App')
.factory('TestService', function() {
(..code to choose what to return but the proper way...)
return {testVar : '22222'}
return {testVar2 : '333333'}
})
.controller('MainCtrl', function (TestService) {
console.log(TestService.testVar);
console.log(TestService.testVar2);
}
.controller('SecCtrl', function (TestService) {
console.log(TestService.testVar);
console.log(TestService.testVar2);
}
I looked at this question, but i think it's more complicated than what I am asking.