I am trying to link two controllers via a factory. I want to set up a pointer in one controller to a value myFactoryVar
on the factory so that when the value in the factory changes, the value controllerVar
in the controller changes.
I've read this post and several like it AngularJS : The correct way of binding to a service properties
but I can't seem to make it work with my code. Maybe it's the format? Maybe I'm binding to a primitive type without meaning to. Here is what I've got so far, any idea how to make it work as intended?
Controller 1:
;(function() {
'use strict';
angular
.module('myapp')
.controller('MyCtrl1', MyCtrl1);
function MyCtrl1(myTracker) {
var vm = this;
angular.extend(vm, {
controllerVar: myTracker.myFactoryVar,
myTrackerVarIncrement: myTrackerVarIncrement
});
function myTrackerVarIncrement() {
myTracker.myFactoryVarIncrement();
/* should log the same value as myFactoryVar but doesn't */
console.log(vm.controllerVar);
}
}
})();
Controller 2:
;(function() {
'use strict';
angular
.module('myapp')
.controller('MyCtrl2', MyCtrl2);
function MyCtrl2(myTracker) {
var vm = this;
angular.extend(vm, {
myTrackerVarIncrement: myTrackerVarIncrement
});
function myTrackerVarIncrement() {
/* I want to be able to increment the value in the factory, */
/* and by means of that, the value in the other controller too */
myTracker.myFactoryVarIncrement();
}
}
})();
Factory:
;(function() {
'use strict';
angular
.module('myapp')
.factory('myTracker', myTracker);
function myTracker() {
var factory = {
myFactoryVar: 1,
myFactoryVarIncrement: myFactoryVarIncrement
};
return factory;
function myFactoryVarIncrement() {
factory.myFactoryVar += 1;
}
}
})();