0

I have two different controller where i am trying to pass variable values to do some actions, I used $broadcast angularJS event but its not working. Is there any other solution to achieve this task ?

I understand there is already question asked regarding variables between controller but i wanted to know what are other possible soultions.

ctrl1.js

$scope.viewAssessmentFrmCycle = function(assessmentId) {
      $scope.$broadcast('viewAssessment',assessmentId);
    }

ctrl2.js

 $scope.$on('viewAssessment',function(s,assessmentId){
                      console.log(assessmentId);
                      $location.path('/rcsa/editAssessmentFromCycle/'+assessmentId+);

                    });
aftab
  • 693
  • 1
  • 12
  • 27

3 Answers3

3

Use a service.

angular.module('myApp', [])
    .service('ShareThis', function () {
        var value = 'myValue';

        return {
            getValue: function () {
                return value;
            },
            setValue: function(newValue) {
                value = newValue;
            }
        };
    });

Then you can access this in each controller by either setting or getting...

Eg:

myApp.controller('Ctrl1', function($scope, ShareThis) {
  $scope.value = ShareThis.getValue();
});

myApp.controller('Ctrl2', function ($scope, ShareThis) {
 $scope.setVal = function(val) {
   ShareThis.setValue(val); 
 }
}
developthewebz
  • 1,827
  • 3
  • 17
  • 43
0

You can create a factory to hold the data.

Factory:

angular.module('myModule').factory('commonData', function(){
  var commonValue = {};
  return {
    getData : function(){ return commonValue },
    setData : function(newData) { commonValue = newData }
  }
});

Then inject this factory into your controller and use the set and get functions to manipulate the data.

S. Simpson
  • 51
  • 4
0

Use factory to hold your data..

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

// create a mediator factory which will persist the data
app.factory("MediatorFactory", function() {
    return {
        obj: {
            value: ""
        }
    };
});

app.controller("FirstCtrl", ["MediatorFactory", function(mediator) {
    this.variable1 = mediator.obj;
}]);

app.controller("SecondCtrl", ["MediatorFactory", function(mediator) {
    this.variable2 = mediator.obj; // this.variable2 = this.variable1 in the controller1
}]);
srinivasan
  • 685
  • 9
  • 18