Pawan Kapoor
Pawan Kapoor

Reputation: 26

AngularJS: Sharing Data between 3 Controllers

I am using factory method in AngularJS to show the combination of First Name and Last Name (first two controllers) as Full Name(in third Controller), but i am not getting the desired output. here is my code:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>
   <div ng-app="myApp">

		<div ng-controller="FirstCtrl">
			<input type="text" ng-model="Data.FirstName">
			<br>FirstName is : <strong>{{Data.FirstName}}</strong>
		</div>
		<hr>
		<div ng-controller="SecondCtrl">
            <input type="text" ng-model="Data.LastName">
			 <br>LastName is : <strong>{{Data.LastName}}</strong>
		</div>
       <div ng-controller="ThirdCtrl">
			FullName is : {{Data.FirstName + " " + Data.LastName}}
		</div>

	</div>
	</div>

    <script>
        var myApp = angular.module('myApp', []);


        myApp.factory('Data', function () {
            return { FirstName: '',LastName:'' };
        });

        myApp.controller('FirstCtrl', function ($scope, Data) {
            $scope.Data = Data;
        });

        myApp.controller('SecondCtrl', function ($scope, Data) {
            $scope.Data = Data;
        });
        myApp.controller('ThirdCrl', function ($scope, Data) {
            $scope.Data = Data;
        }); 
    </script>
</body>
</html>

Can you please Help?

Upvotes: 1

Views: 71

Answers (2)

Gopinath Shiva
Gopinath Shiva

Reputation: 3892

It seems you have spelled wrongly the third controller name.

Upvotes: 0

Joe Enzminger
Joe Enzminger

Reputation: 11190

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>

<body>
   <div ng-app="myApp">

		<div ng-controller="FirstCtrl">
			<input type="text" ng-model="Data.FirstName">
			<br>FirstName is : <strong>{{Data.FirstName}}</strong>
		</div>
		<hr>
		<div ng-controller="SecondCtrl">
            <input type="text" ng-model="Data.LastName">
			 <br>LastName is : <strong>{{Data.LastName}}</strong>
		</div>
       <div ng-controller="ThirdCtrl">
			FullName is : {{Data.FirstName + " " + Data.LastName}}
		</div>

	</div>
	</div>

    <script>
        var myApp = angular.module('myApp', []);


        myApp.factory('Data', function () {
            return { FirstName: '',LastName:'' };
        });

        myApp.controller('FirstCtrl', function ($scope, Data) {
            $scope.Data = Data;
        });

        myApp.controller('SecondCtrl', function ($scope, Data) {
            $scope.Data = Data;
        });
        myApp.controller('ThirdCtrl', function ($scope, Data) {
            $scope.Data = Data;
        }); 
    </script>
</body>
</html>

Upvotes: 1

Related Questions