Introduction
In one of my projects I encountered the situation where I needed to use the model value of one page on another page and these pages were in a parent-child relationship, in other words one page was opening in another one. At that time I came to understand that if we are in such a situation, we can call the model of the child on the parent page. This can be done in various ways, but here I will show the simplest one. In other words using the $parent directive of Angular. Let's understand this using a simple example.
Step 1
First of all I created a parent page. On this page I just created a div that is used to call the controller. Under this div I used a h1 tag, a button and one more div that will be used to include our child page. So, the code is something as in the following:
- <!DOCTYPE html>
- <html>
-
- <head>
- <script src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
- <link href="style.css" rel="stylesheet" />
- <script src="script.js"></script>
- </head>
-
- <body ng-app>
- <div ng-controller="TestCtrl">
- <h1>{{value}}</h1>
- <div ng-include="'test.html'"></div>
- <button ng-click="fetch()">Go!!</button>
- </div>
- </body>
- </html>
Step 2
After this I created a child page and on this page a simple TextBox is used whose value will be used in the model and this model will be used in the parent page.
But this model is different from other models, in other words because the $parent is written with it, that will allow the parent controller to access it. So, its scope is now extended to its parent. So only a single line of code is written on this page.
- <input type="text" placeholder="Enter your name" ng-model="$parent.value">
Step 3
After this I worked on the .js file that has the following code:
- var TestCtrl = function($scope){
- $scope.fetch = function(){
- alert($scope.value);
- };
- };
Here a controller is created whose name is "TestCtrl". In this controller two $scopes are defined, the first one is the model that is called on the button click that was available on the parent page and the second $scope has the model value that was provided at the child page. The second $scope value will be alerted that will confirm that our code is working properly.
Output
On running the application you can see that I got a TextBox and a button, the TextBox was available on the child page and the button was on the parent page.
After this I wrote my name and as you can see the same name is provided by the h1 tag also, which means that our AngularJs is working properly.
As I click on the button, the same name can be seen in the alert box as well.
As I said in the beginning of this article, that this is only one way to do this, there are other ways as well that will be described in my future article, so stay tuned.