Skip to content Skip to sidebar Skip to footer

Angularjs - Sharing Variables Between Controllers

I know this has been posted before but I am still confused on how to achieve this for my specific problem. my first controller: myApp.controller('buttonCtrl', function($scope){

Solution 1:

Use Angular JS Services/ Factories

A sample example is shown below

Working Demo

HTML

<divng-app='myApp'><divng-controller="ControllerOne"><buttonng-click="getUserOne()">User One</button></div><divng-controller="ControllerTwo"><buttonng-click="getUserTwo()">User Two</button></div></div>

SCRIPT

var app = angular.module('myApp', []);

app.factory('userFactory', function () {
    return {
        users: [{
            userId: 1,
            userName: "Jhonny"
        }, {
            userId: 2,
            userName: "Sunny"
        }]
    }
});

app.controller('ControllerOne', function ($scope, userFactory) {
    $scope.getUserOne = function () {
        alert(JSON.stringify(userFactory.users[0]));
    }

});

app.controller('ControllerTwo', function ($scope, userFactory) {
    $scope.getUserTwo = function () {
        alert(JSON.stringify(userFactory.users[1]));
    }

});

Also take a look at this stuff

How can I pass variables between controllers in AngularJS?

Post a Comment for "Angularjs - Sharing Variables Between Controllers"