My current setup involves updating data stored in a service and shared with the controller to display in the view.
The example showcases two variables - one holding an array and the other just a string.
One thing that puzzles me is why does the array get updated and displayed in the view, but not the string?!
JavaScript:
function fooService() {
var mystring = 'old string';
var myarray = [];
var updateArray = function(data) {
myarray.push(data);
};
var updateString = function(data) {
mystring = data;
};
return {
myarray: myarray,
mystring: mystring,
updateString: updateString,
updateArray: updateArray
}
}
function MainCtrl($scope, fooService) {
this.myarray = fooService.myarray;
this.mystring = fooService.mystring;
}
function fooDirective(fooService) {
function link(scope) {
fooService.updateArray(scope.vm.name);
fooService.updateString('new string');
}
return {
restrict: 'EA',
replace: true,
template: '<h2 style="color: {{vm.color}};">{{vm.name}}</h2>',
scope: {},
controller: 'MainCtrl',
controllerAs: 'vm',
bindToController: {
name: '@',
color: '@'
},
link: link
};
}
angular
.module('app', [])
.service('fooService', fooService)
.controller('MainCtrl', MainCtrl)
.directive('fooDirective', fooDirective);
HTML:
<div ng-app="app">
<div ng-controller="MainCtrl as vm">
{{vm.myarray}}
{{vm.mystring}}
<foo-directive data-name="Markus" data-color="red"></foo-directive>
<foo-directive data-name="Nemanja" data-color="green"></foo-directive>
<foo-directive data-name="Luke" data-color="blue"></foo-directive>
</div>
</div>
I may have misunderstood, but isn't the purpose of services to store data shared across the app?
See the working example here: http://jsfiddle.net/markus_falk/f00y3tL3/6/