0

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

Foo Stack
  • 2,185
  • 7
  • 24
  • 25

4 Answers4

0

You should use an intermediate object and it's property directly.

Like this.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
0
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'];
Jesse Earle
  • 1,622
  • 1
  • 11
  • 13
0

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

kapv89
  • 1,692
  • 1
  • 17
  • 20
0

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'];
e82
  • 146
  • 2
  • 2