AngularJS: How can I pass variables between controllers?

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

    Solution without creating Service, using $rootScope:

    To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

    The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.

    var app = angular.module('mymodule',[]);
    app.controller('Ctrl1', ['$scope','$rootScope',
      function($scope, $rootScope) {
        $rootScope.showBanner = true;
    }]);
    
    app.controller('Ctrl2', ['$scope','$rootScope',
      function($scope, $rootScope) {
        $rootScope.showBanner = false;
    }]);
    

    Using $rootScope in a template (Access properties with $root):

提交回复
热议问题