Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value between two javascript files

I have implemented a calender and on click I am getting the specified days. Snippet from Calender.js:

$scope.checkDate = function(key){
    $scope.dateKey = key - 1;
    alert("left")
    alert($scope.dateKey)
      if ($scope.dateKey>=1){
          alert("Testing")

      }
    if(dateKey == 0) {
      $rootScope.loadNextDay = true;
     alert("right")
    }
  };

Now the value of dateKey I am getting is somewhere from 0 to 6 depending on the day selected. Now I am trying to use the variable ie $scope.dateKey in another js file(a new one). Snippet of application.js:-

  if($scope.currentDate = true && shift==0)
  {
    alert("Hey.....")
      alert($scope.dateKey)

  }
    else{
      alert("Testing123")
    $scope.moveTo(0);
    $scope.currentDate = false;
    $timeElapsed.hide();
    params.starthour = 0;
}

But in this $scope.dateKey is giving undefined. What should I do to use the value of dateKey from calender.js to application.js?


1 Answers

The best way to share information across multiple controllers are services, since services are singletons it's easier to manage a and isolate a scope/variables for that purpose.

a basic example:

var app = angular.module('myApp', []);
app.factory('datepickerinfo', function() {
    var keyValue;

    datepickerinfo.setKey = function(key) {
    keyValue = key;
    };
    datepickerinfo.getKey = function(){
    return keyValue;
    }

    return datepickerinfo;
});

//you can inject your dependency and share the it across multiple controllers

function MyCtrl($scope, datepickerinfo) {
    $scope.dateKey = datepickerinfo.getKey();
}

take a look to this question for further reference.

there's other option, write to a $rootscope, and rise an event using a emit it worth to mention that emit seems to be more efficient rather than $broadcast

$emit: Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

like image 119
pedrommuller Avatar answered Mar 22 '26 18:03

pedrommuller