AngularJS: How can I pass variables between controllers?

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

I have two Angular controllers:

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

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


        
16条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 01:19

    One way to share variables across multiple controllers is to create a service and inject it in any controller where you want to use it.

    Simple service example:

    angular.module('myApp', [])
        .service('sharedProperties', function () {
            var property = 'First';
    
            return {
                getProperty: function () {
                    return property;
                },
                setProperty: function(value) {
                    property = value;
                }
            };
        });
    

    Using the service in a controller:

    function Ctrl2($scope, sharedProperties) {
        $scope.prop2 = "Second";
        $scope.both = sharedProperties.getProperty() + $scope.prop2;
    }
    

    This is described very nicely in this blog (Lesson 2 and on in particular).

    I've found that if you want to bind to these properties across multiple controllers it works better if you bind to an object's property instead of a primitive type (boolean, string, number) to retain the bound reference.

    Example: var property = { Property1: 'First' }; instead of var property = 'First';.


    UPDATE: To (hopefully) make things more clear here is a fiddle that shows an example of:

    • Binding to static copies of the shared value (in myController1)
      • Binding to a primitive (string)
      • Binding to an object's property (saved to a scope variable)
    • Binding to shared values that update the UI as the values are updated (in myController2)
      • Binding to a function that returns a primitive (string)
      • Binding to the object's property
      • Two way binding to an object's property

提交回复
热议问题