AngularJS: How can I pass variables between controllers?

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

    The following example shows how to pass variables between siblings controllers and take an action when the value changes.

    Use case example: you have a filter in a sidebar that changes the content of another view.

    angular.module('myApp', [])
    
      .factory('MyService', function() {
    
        // private
        var value = 0;
    
        // public
        return {
          
          getValue: function() {
            return value;
          },
          
          setValue: function(val) {
            value = val;
          }
          
        };
      })
      
      .controller('Ctrl1', function($scope, $rootScope, MyService) {
    
        $scope.update = function() {
          MyService.setValue($scope.value);
          $rootScope.$broadcast('increment-value-event');
        };
      })
      
      .controller('Ctrl2', function($scope, MyService) {
    
        $scope.value = MyService.getValue();
    
        $scope.$on('increment-value-event', function() {    
          $scope.value = MyService.getValue();
        });
      });
    
    
    

    Controller 1 Scope


    Controller 2 Scope

    Value: {{ value }}

提交回复
热议问题