1

I tried sharing data between two controllers using a factory. For some reason, the two inputs don't share data. In the AppCtrl controller I assign Data.FirstName to equal lattitude. But when I get to the PathController, I can't read the value stored in Data.FirstName.
Can anyone let me know what is wrong with my code?

 .factory('Data', function(){ return { FirstName: 'jjjj' }; }) // controller one .controller('AppCtrl', function($scope, Data, $http, $ionicModal, $timeout) { .... $scope.mapLocation = function(lattitude, longittude) { Data.FirstName = lattitude; $scope.Data = Data; } .... }) // controller two .controller("PathController", [ '$scope', function($scope, Data) { $scope.Data = Data; console.log(Data.FirstName); // Not getting Data.FirstName angular.extend($scope, { center: { lat: 35.720031000963, lng: -87.343068987131, zoom: 17 }, markers: { Campus: { lat: 35.728031000963, lng: -87.343068987131, focus: true, draggable: false, message: "Building1" }, }, defaults: { scrollWheelZoom: false } }); }]) 
2
  • Are you calling mapLocation anywhere? Can you show where? Commented Sep 15, 2015 at 6:05
  • You have to use an object type in $scope if you want to inherit a property from global scope.To understand clearly please read more at here [Understanding-Scopes][1] [1]: github.com/angular/angular.js/wiki/Understanding-Scopes Commented Sep 15, 2015 at 6:15

3 Answers 3

1

change the data factory like this

.factory('Data', function(){ return { mydata: { FirstName: 'jjjj' } }; }) 

and assign as follows

Data.mydata.FirstName = lattitude; $scope.Data = Data.mydata; 
Sign up to request clarification or add additional context in comments.

Comments

0

I think you forget to add the factory as parameter. Try this

.controller("PathController", [ '$scope', function($scope, Data) {

1 Comment

It should be .controller("PathController", [ '$scope', 'Data', function($scope, Data) {, please fix it
0

I am not sure, but try this:

.service('Data', function(){ var FirstName = 'jjjj'; return { FirstName: FirstName }; }) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.