I've created a simple app that share data between controllers. A button increment a variable number value in a controller (A) and then it shares data with other controller (B)
Factory can't return primitives variables, right? So I declared an object. The problem is that getList() can't return the object property data.product, it is always an empty string.
When I return the full object, it works fine. scope.total in ControllerB is {"product":x}
What would be the best way to achieve this? I only need to share the variable scope.total from one controller to the other one, not the full object.
HTML
<div ng-app="tabsApp">
<div id="London" class="tabcontent">
<div ng-controller="tabOneController as vm">
<input type="button" value="add" ng-click="vm.addMore()"/>
</div>
</div>
<div id="Paris" class="tabcontent">
<div ng-controller="tabTwoController as vm">
<span>{{vm.total}}</span>
</div>
</div>
</div>
JS
angular
var app = angular.module('tabsApp', []);
app.controller("tabOneController", controllerA);
app.controller("tabTwoController", controllerB);
app.factory('myData', function() {
var data = {
product: ''
};
function addItem(value) {
data.product = value;
}
function getList() {
return data;
}
return {
addItem: addItem,
getList: getList
};
});
function controllerA(myData){
var scope = this;
scope.total = 0;
scope.addMore = function(){
scope.total++;
myData.addItem(scope.total);
}
}
function controllerB(myData){
var scope = this;
scope.total = myData.getList();
}