2

I want to declare a variable that I want to use in my two controllers. One controller is for posting values and the second controller is used for getting values from the db. I have used a factory and it returns the time stamp.

This is my code:

mainApp.factory('methodFactory', function () {
    return { myMethod: function () {
            var date = new Date();
    //console.log(date);
var unique = ((date.getMonth()+1) + '' + date.getDate() + '' +  date.getFullYear() + ''+ date.getHours() +''+ date.getMinutes() +''+ date.getSeconds());
        return unique;
            //console.log("methodFactory - myMethod");
    }
}
});

When I use methodFactory() in my controllers, the values have changed. Is there any way to have the same values in both of the controllers.

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63
Ranjeet singh
  • 794
  • 1
  • 16
  • 38

2 Answers2

0

It is normal since myMethod() function returns always a new Date(). You don't store the information in the current object.

Store the computed unique variable in a service and provide a getter and a setter to the value in this service.

here a simple example with two controllers where the first controller sets the value in the service and the second controller gets the value from the service: http://plnkr.co/edit/4WRtfVF3DnOfPDXz9mq0?p=preview

js

var app = angular.module('plunker', []);

app.controller('MainCtrl', MainCtrl);
app.controller('SecondCtrl', SecondCtrl);



function MainCtrl($scope, sharedDataService) {

  $scope.setDate= function(){
    var date = new Date();
    var unique = ((date.getMonth()+1) + '' + date.getDate() + '' +  date.getFullYear() + ''+ date.getHours() +''+ date.getMinutes() +''+ date.getSeconds());
     sharedDataService.setDate(unique);
  }

}

function SecondCtrl($scope, sharedDataService) {

  $scope.getDate=function(){
    return sharedDataService.getDate();
  } 
}



app.service('sharedDataService', function() {
      var uniqueDate;

       this.getDate = function() {
        return uniqueDate;
      }

      this.setDate= function(newDate) {
        uniqueDate=newDate;
      }       
});

html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
    <script src="app.js"></script>
  </head>

  <body>
    <div ng-controller="MainCtrl">
       <button ng-click="setDate()">submit</button>
    </div>
    <div ng-controller="SecondCtrl">
      <div>{{getDate()}}</div>
    </div>
  </body>

</html>
davidxxx
  • 125,838
  • 23
  • 214
  • 215
0
  • declare using a $rootScope or declare in a service

find the reference Global variables in AngularJS

Community
  • 1
  • 1
Naghaveer R
  • 2,890
  • 4
  • 30
  • 52