AngularJS: How can I pass variables between controllers?

后端 未结 16 2577
误落风尘
误落风尘 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: '<div><input type="text" ng-model="model.value"/></div>'
      }
    }]);
    

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

    0 讨论(0)
  • 2020-11-22 01:22

    Second Approach :

    angular.module('myApp', [])
      .controller('Ctrl1', ['$scope',
        function($scope) {
    
        $scope.prop1 = "First";
    
        $scope.clickFunction = function() {
          $scope.$broadcast('update_Ctrl2_controller', $scope.prop1);
        };
       }
    ])
    .controller('Ctrl2', ['$scope',
        function($scope) {
          $scope.prop2 = "Second";
    
            $scope.$on("update_Ctrl2_controller", function(event, prop) {
            $scope.prop = prop;
    
            $scope.both = prop + $scope.prop2; 
        });
      }
    ])
    

    Html :

    <div ng-controller="Ctrl2">
      <p>{{both}}</p>
    </div>
    
    <button ng-click="clickFunction()">Click</button>
    

    For more details see plunker :

    http://plnkr.co/edit/cKVsPcfs1A1Wwlud2jtO?p=preview

    0 讨论(0)
  • 2020-11-22 01:26

    The sample above worked like a charm. I just did a modification just in case I need to manage multiple values. I hope this helps!

    app.service('sharedProperties', function () {
    
        var hashtable = {};
    
        return {
            setValue: function (key, value) {
                hashtable[key] = value;
            },
            getValue: function (key) {
                return hashtable[key];
            }
        }
    });
    
    0 讨论(0)
  • 2020-11-22 01:27

    Besides $rootScope and services, there is a clean and easy alternative solution to extend angular to add the shared data:

    in the controllers:

    angular.sharedProperties = angular.sharedProperties 
        || angular.extend(the-properties-objects);
    

    This properties belong to 'angular' object, separated from the scopes, and can be shared in scopes and services.

    1 benefit of it that you don't have to inject the object: they are accessible anywhere immediately after your defination!

    0 讨论(0)
提交回复
热议问题