Home >Web Front-end >JS Tutorial >How Can I Effectively Pass Variables Between AngularJS Controllers?

How Can I Effectively Pass Variables Between AngularJS Controllers?

DDD
DDDOriginal
2024-12-02 01:32:14244browse

How Can I Effectively Pass Variables Between AngularJS Controllers?

Passing Variables Between AngularJS Controllers

Passing variables between AngularJS controllers is a common task in application development. One approach is to create a service to share variables across controllers.

Creating a Shared Service

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Using the Service

In controllers, inject the shared service:

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

Considerations

For bindings to work across controllers, it's preferable to bind to an object's property rather than a primitive type.

// Avoid using primitive types
var property = 'First';

// Use objects
var property = { Property1: 'First' };

Example

See [this fiddle](https://jsfiddle.net/philipjohnson/34qhw/) for an example that demonstrates:

  • Binding to static copies of shared values
  • Binding to shared values that update the UI as values change

    • Binding to a function
    • Binding to an object's property
    • Two-way binding to an object's property

The above is the detailed content of How Can I Effectively Pass Variables Between AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn