AngularJS: How can I pass variables between controllers?

后端 未结 16 2916
误落风尘
误落风尘 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: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 :

    {{both}}

    For more details see plunker :

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

提交回复
热议问题