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+);

                    });
1
  • i edited my question Commented Jan 13, 2016 at 13:46

3 Answers 3

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); 
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That make sense thanks for the help
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.

Comments

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
}]);

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.