Click here to Skip to main content
15,921,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am new to AngularJS. i am having a following functionality where i am having a FirstName field and LastName Field(in two Different Controllers) and then on the click of a button i want to show FullName(First Name + Last Name) in a third Controller . Please Suggest me how to do. Here is my code:

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

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

       <h2>Controller 1</h2><br />
        <div ng-controller="FirstCtrl">
            <input type="text" ng-model="Data.FirstName">
            <br>FirstName is : <strong>{{Data.FirstName}}</strong>
        </div>
        <hr>
       <h2>Controller 2</h2><br />
        <div ng-controller="SecondCtrl">
            <input type="text" ng-model="Data.LastName">
             <br>LastName is : <strong>{{Data.LastName}}</strong>
        </div>
      <h2>Controller 3</h2><br />
       <div ng-controller="ThirdCtrl">
           <button ng-click="getName(Data)">Get full Name</button>
            FullName is : {{getName(Data)}}

        </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;
            $scope.getName = Data;
        });
    </script>
</body>
</html>
Posted

1 solution

Consider using a "Service". The video below can be a good start.

https://egghead.io/lessons/angularjs-sharing-data-between-controllers[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900