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
Release: 2024-12-02 01:32:14
Original
241 people have browsed it

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;
            }
        };
    });
Copy after login

Using the Service

In controllers, inject the shared service:

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

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' };
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template