You should use an intermediate object and it's property directly.
Unable to share data between AngularJS controllers?
Question
I had seen the egghead.io video on sharing data between controllers, but couldn't get it to work:
var myApp = angular.module('myApp', []);
myApp.factory('QData', function () {
return 'hello'
});
function QCtrl($scope, $http, QData) {
$scope.foo = QData;
}
QCtrl.$inject = ['$scope', '$http', 'QData'];
function YCtrl($scope, $http, QData) {
$scope.bar = QData;
}
YCtrl.$inject = ['$scope', '$http', 'QData'];
See code (with additional bootstrap view) running on Plnkr
Solution
OTHER TIPS
var myApp = angular.module('myApp', []);
myApp.factory('QData', function () {
return 'hello'
});
function ParentCtrl($scope, $http, QData) {
$scope.foo = 'My data';
}
QCtrl.$inject = ['$scope', '$http', 'QData'];
function QCtrl($scope, $http, QData) { }
QCtrl.$inject = ['$scope', '$http', 'QData'];
function YCtrl($scope, $http, QData) { }
YCtrl.$inject = ['$scope', '$http', 'QData'];
I think the problem arises because your factory is returning a string. And strings behave differently from objects in js (iirc, they are wrapped up into objects when they are treated as them, otherwise they are primitives). For example
var a = 'hello';
var b = a;
a.x = 1;
console.log(b.x) //undefined
var a = {x: 1}; var b=a; a.y = 1; console.log(b.y); //1
basically, it'd be better if you work with objects, like here : http://plnkr.co/edit/zqCPn9?p=preview
If your service is changing QData, and not a property within QData - Angular loses track of the object reference, and the other controllers don't know what's going on.
Tweaked your code and added a use of $timeout to simulate something like an $http request updating your QData. Forked your plunker - but relevant JS code below.
'use strict';
var myApp = angular.module('myApp', []);
myApp.factory('QData', function () {
return { text: 'hello' } ;
});
function QCtrl($scope, $http, QData, $rootScope) {
$scope.foo = QData;
}
QCtrl.$inject = ['$scope', '$http', 'QData', '$rootScope'];
function YCtrl($scope, $http, QData, $rootScope,$timeout) {
$scope.bar = QData;
$rootScope.globe = 5;
$timeout(function()
{
QData.text = "Test!"
},5000);
}
YCtrl.$inject = ['$scope', '$http', 'QData', '$rootScope','$timeout'];