AngularJS: How can I pass variables between controllers?

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

    I like to illustrate simple things by simple examples :)

    Here is a very simple Service example:

    
    angular.module('toDo',[])
    
    .service('dataService', function() {
    
      // private variable
      var _dataObj = {};
    
      // public API
      this.dataObj = _dataObj;
    })
    
    .controller('One', function($scope, dataService) {
      $scope.data = dataService.dataObj;
    })
    
    .controller('Two', function($scope, dataService) {
      $scope.data = dataService.dataObj;
    });
    

    And here the jsbin

    And here is a very simple Factory example:

    
    angular.module('toDo',[])
    
    .factory('dataService', function() {
    
      // private variable
      var _dataObj = {};
    
      // public API
      return {
        dataObj: _dataObj
      };
    })
    
    .controller('One', function($scope, dataService) {
      $scope.data = dataService.dataObj;
    })
    
    .controller('Two', function($scope, dataService) {
      $scope.data = dataService.dataObj;
    });
    

    And here the jsbin


    If that is too simple, here is a more sophisticated example

    Also see the answer here for related best practices comments

提交回复
热议问题