AngularJS: How can I pass variables between controllers?

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

I have two Angular controllers:

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

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


        
16条回答
  •  Happy的楠姐
    2020-11-22 01:01

    I tend to use values, happy for anyone to discuss why this is a bad idea..

    var myApp = angular.module('myApp', []);
    
    myApp.value('sharedProperties', {}); //set to empty object - 
    

    Then inject the value as per a service.

    Set in ctrl1:

    myApp.controller('ctrl1', function DemoController(sharedProperties) {
      sharedProperties.carModel = "Galaxy";
      sharedProperties.carMake = "Ford";
    });
    

    and access from ctrl2:

    myApp.controller('ctrl2', function DemoController(sharedProperties) {
      this.car = sharedProperties.carModel + sharedProperties.carMake; 
    
    });
    

提交回复
热议问题