AngularJS: How can I pass variables between controllers?

后端 未结 16 2575
误落风尘
误落风尘 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();
        });
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="myApp">
      
      <h3>Controller 1 Scope</h3>
      <div ng-controller="Ctrl1">
        <input type="text" ng-model="value"/>
        <button ng-click="update()">Update</button>
      </div>
      
      <hr>
      
      <h3>Controller 2 Scope</h3>
      <div ng-controller="Ctrl2">
        Value: {{ value }}
      </div>  
    
    </div>

    0 讨论(0)
  • 2020-11-22 01:00

    I looked thru the answers above, I recommend pejman's Dec 29 '16 at 13:31 suggestion but he/she has not left a full answer. Here it is, I will put this as --> (you need a service and a listener $watch on one of the scopes from controllers for changes in the service area)

    var app = 
    angular.module('myApp', ['ngRoute', 'ngSanitize']);
    
    app.service('bridgeService', function () {
        var msg = ""; 
        return msg;
    });
    app.controller('CTRL_1'
    , function ($scope, $http, bridgeService) 
    {
        $http.get(_restApi, config)
        .success(
        function (serverdata, status, config) {
            $scope.scope1Box = bridgeService.msg = serverdata;
        });
    });
    app.controller('CTRL_2'
    , function ($scope, $http, bridgeService) 
    {
        $scope.$watch( function () {
            return (bridgeService.msg);
        }, function (newVal, oldVal) {
            $scope.scope2Box = newVal;
        }, true
        );
    });
    
    0 讨论(0)
  • 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; 
    
    });
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 01:06

    You could do that with services or factories. They are essentially the same apart for some core differences. I found this explanation on thinkster.io to be the easiest to follow. Simple, to the point and effective.

    0 讨论(0)
  • 2020-11-22 01:08

    Ah, have a bit of this new stuff as another alternative. It's localstorage, and works where angular works. You're welcome. (But really, thank the guy)

    https://github.com/gsklee/ngStorage

    Define your defaults:

    $scope.$storage = $localStorage.$default({
        prop1: 'First',
        prop2: 'Second'
    });
    

    Access the values:

    $scope.prop1 = $localStorage.prop1;
    $scope.prop2 = $localStorage.prop2;
    

    Store the values

    $localStorage.prop1 = $scope.prop1;
    $localStorage.prop2 = $scope.prop2;
    

    Remember to inject ngStorage in your app and $localStorage in your controller.

    0 讨论(0)
提交回复
热议问题