1

I have these controller codes from different js files.

NLGoalsCtrl.js

angular.module('mysite').controller('NLGoalsCtrl', function ($scope) {
    $scope.goals_selected = [];
});

NLSessionsCtrl.js

angular.module('mysite').controller('NLSessionsCtrl', function ($scope) {
    //access $scope.goals_selected here
});

I need to be able to access the $scope.goals_selected from the NLSessionsCtrl. How do I do this? Thanks guys.

3
  • 1
    you could have angular service which will responsible for sharing data amongst you controller Commented Jan 7, 2016 at 14:43
  • You'll probably want to use an angular service to share that data, as scopes are local to a controller. Commented Jan 7, 2016 at 14:43
  • You're going to want to use a service to share this code across controllers. docs.angularjs.org/guide/services Commented Jan 7, 2016 at 14:43

3 Answers 3

3

Use a factory/service to store the goals which will be responsible for sharing data among the controllers.

myApp.factory('myService', [function() {
        var goals = {};
        return {
            getGoals: function() {
                return goals
            },

            setGoals: function(op) {
                goals = op;
            },
        }
    }])
    .controller('NLGoalsCtrl', [function($scope, myService) {
        $scope.goals_selected  = {};
        //Update goals_selected
        myService.setGoals($scope.goals_selected );
    }])
    .controller('NLSessionsCtrl', [function($scope, myService) {
        //Fetch
        $scope.goals_selected  = myService.getGoals();
    }]);
Sign up to request clarification or add additional context in comments.

2 Comments

will this really work? I mean what if goal_selected is modified from view after execution of myService.setGoals($scope.goals_selected)? In this case myService.getGoals() will give me updated values or a stale copy of data?
You should use a pointer to the variable, not a function. That way you will always keep it in sync, meaning that angular registers changes and because the pointers are the same, it will also update in the other controller. OR you will need to set watchers in your controllers, which will evaluate the factory functions
1

$scope is an "object" that "binds" to DOM element where you apply controller. So the context of $scope remains inside the controller.

If you want to access the variables in 2 controllers , try to share it via a service/Factory or $rootScope

Here is a sample App

Comments

0

the one that you want to access in any controller assign it to the $rootScope. and access it in any controller you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.