AngularJS: How can I pass variables between controllers?

后端 未结 16 2610
误落风尘
误落风尘 2020-11-22 00:31

I have two Angular controllers:

function Ctrl1($scope) {
    $scope.prop1 = \"First\";
}

function Ctrl2($scope) {
    $scope.prop2 = \"Second\";
    $scope.         


        
16条回答
  •  鱼传尺愫
    2020-11-22 01:21

    I'd like to contribute to this question by pointing out that the recommended way to share data between controllers, and even directives, is by using services (factories) as it has been already pointed out, but also I'd like to provide a working practical example of how to that should be done.

    Here is the working plunker: http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=info

    First, create your service, that will have your shared data:

    app.factory('SharedService', function() {
      return {
        sharedObject: {
          value: '',
          value2: ''
        }
      };
    });
    

    Then, simply inject it on your controllers and grab the shared data on your scope:

    app.controller('FirstCtrl', function($scope, SharedService) {
      $scope.model = SharedService.sharedObject;
    });
    
    app.controller('SecondCtrl', function($scope, SharedService) {
      $scope.model = SharedService.sharedObject;
    });
    
    app.controller('MainCtrl', function($scope, SharedService) {
      $scope.model = SharedService.sharedObject;
    });
    

    You can also do that for your directives, it works the same way:

    app.directive('myDirective',['SharedService', function(SharedService){
      return{
        restrict: 'E',
        link: function(scope){
          scope.model = SharedService.sharedObject;
        },
        template: '
    ' } }]);

    Hope this practical and clean answer can be helpful to someone.

提交回复
热议问题