This article is a continuation of my previous article. If you haven’t had a look at it please go through the following link:
Creating Custom Directives In AngularJS - Part1 We’ll get into the theory a bit later. Firstly, we will focus on the architecture of the application used for demonstrating this article. I am using VS2013 ASP.NET MVC 4 application, AngularJS, Bootstrap and jQuery.
I have created ASP.NET MVC 4 application and added the necessary AngularJS and bootstrap libraries and defined a custom AngularJS directive with the name “contactInfo.html”.
contactInfo.html - <div class="list-group">
- <a href="#" class="list-group-item" ng-repeat="person in Persons">
- <h3 class="list-group-item-heading">
- {{person.Name}}
- </h3>
- <h5 class="list-group-item-text">
- {{person.Address}}
- </h5>
- <h6 class="list-group-item-text">
- {{person.ContactNo}}
- </h6>
- </a>
- </div>
I have updated my _Layout.cshtml file to include bootstrap and AngularJS links.
_Layout.cshtml- <!DOCTYPE html>
- <html ng-app="myApp">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width" />
- <title>@ViewBag.Title</title>
- @Scripts.Render("~/bundles/jquery")
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/Scripts/angular.min.js"></script>
- </head>
- <body>
- @RenderBody()
-
- @RenderSection("scripts", required: false)
- </body>
- </html>
I have added a new folder inside our Script folder with the name “app” and added a new javascript file name
“Home.js” to the app folder.
Index.cshtml- @{
- ViewBag.Title = "Index";
- }
-
- <script src="~/Scripts/app/Home.js"></script>
- <div class="container" ng-controller="homeController">
- <div class="row">
- <div class="col-md-12">
- <div ng-app="myApp" style="width:400px;">
- <div ng-controller="homeController">
- <h3>Person Details</h3>
- <div class="list-group">
- <contact-info></contact-info>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
Now we are all set with the architecture of the application and everything is in place, so let’s move towards a bit of theory.
Well there are 3 ways through which you can define your $scope object behavior within custom AngularJS directives. They are the following:
Shared Scope
From the above link demo we can conclude that $scope object inside our controller is accessible in our directives also i.e. whatever models or function we define on our controller $scope we can access all of them inside our custom AngularJS directive. This is what we call as Shared Scope. By default controller $scope object would be shared with our custom AngularJS directives. Any changes made to the scope object inside our custom AngularJS directive will have a reflection in the controller $scope object and vice versa. To explore more into this let’s look at the following demo. Here is the updated
“Home.js” file.
Home.js - var myApp = angular.module("myApp", []);
- myApp.controller("homeController", ["$scope", function ($scope) {
- $scope.Persons = [
- { Name: "Vishal Gilbile", Address: "132 Lions Street Andheri (E)", ContactNo: '9820109742' },
- { Name: "Rahul Bandekar", Address: "135 Lions Street Andheri (E)", ContactNo: '9820109748' }
- ];
- }]);
-
-
- myApp.directive("contactInfo", function () {
- return {
- restrict: "AE",
- templateUrl: '../../Directives/contactInfo.html',
- replace: false
- }
- });
Let’s run the application and here is the output.
Figure 1: Person Detail
Now let’s update the $scope model inside our custom AngularJS controller to prove that the scope object is shared between the two (i.e. between controller and custom directive).
Here's the updated custom angular directive code snippet.
- myApp.directive("contactInfo", function ()
- {
- return {
- restrict: "AE",
- templateUrl: '../../Directives/contactInfo.html',
- replace: false,
- controller: function ($scope) {
- $scope.Persons.push({ Name: "Shrikant Maharana", Address: "1324 Lions Street Andheri (W)", ContactNo: "9820104874" });
- }
- }
- });
- We’ve updated our Custom AngularJS directive and also we’ve provided it with its own controller having $scope object injected.
- We tried updating the $scope.Person model by adding a new person data to it inside our custom AngularJS directive.
Let’s try to run the application and here is the output.
Figure 2: Detail
So we are now getting 3 records (2 from controller and 1 from our AngularJS custom directive). So we proved our point that the $scope object was shared between the controller and the custom directive.
Inherited Scope
Within this our $scope object will be inherited from controller $scope object. Custom directive $scope object will still be able to access/update the model of $scope object of the controller. But if we create some model data inside our custom directive $scope object this model will only be accessible within the directives and not to the controller $scope object. For implementing this $scope behavior we just need to add the scope property with value true to our custom directive. For demonstrating this we’ve added a new model to the custom directive $scope object named “count” which displays the count of records from the model.
contactInfo.html
- <div class="list-group">
- <a href="#" class="list-group-item" ng-repeat="person in Persons">
- <h3 class="list-group-item-heading">
- {{person.Name}}
- </h3>
- <h5 class="list-group-item-text">
- {{person.Address}}
- </h5>
- <h6 class="list-group-item-text">
- {{person.ContactNo}}
- </h6>
- </a>
- <h6><strong>{{count}} Records Found.</strong></h6>
- </div>
Home.js - myApp.directive("contactInfo", function ()
- {
- return {
- restrict: "AE",
- templateUrl: '../../Directives/contactInfo.html',
- replace: false,
- scope: true,
- controller: function ($scope) {
- $scope.count = 0;
- $scope.Persons.push({ Name: "Shrikant Maharana", Address: "1324 Lions Street Andheri (W)", ContactNo: "9820104874" });
- $scope.count = $scope.Persons.length;
- }
- }
- });
Let’s run the application.
Figure 3: Run the Application
Now let’s try to access the “
count” model inside our controller $scope. For demonstrating this I’ve updated some piece of code. Here is the updated code snippet.
Index.cshtml - @{
- ViewBag.Title = "Index";
- }
- <script src="~/Scripts/app/Home.js"></script>
- <div class="container" ng-controller="homeController">
- <div class="row">
- <div class="col-md-12">
- <div ng-app="myApp" style="width:400px;">
- <div ng-controller="homeController">
- <h3>Person Details</h3>
- <contact-info></contact-info>
- <label>Controller Count Value: {{count}}</label>
- </div>
- </div>
- </div>
- </div>
- </div>
Home.js - var myApp = angular.module("myApp", []);
-
-
- myApp.controller("homeController", ["$scope", function ($scope) {
- $scope.Persons = [
- { Name: "Vishal Gilbile", Address: "132 Lions Street Andheri (E)", ContactNo: '9820109742' },
- { Name: "Rahul Bandekar", Address: "135 Lions Street Andheri (E)", ContactNo: '9820109748' }
- ];
- $scope.count = 0;
- }]);
-
-
- myApp.directive("contactInfo", function () {
- return {
- restrict: "AE",
- templateUrl: '../../Directives/contactInfo.html',
- replace: false,
- scope: true,
- controller: function ($scope) {
- $scope.count = 0;
- $scope.Persons.push({ Name: "Shrikant Maharana", Address: "1324 Lions Street Andheri (W)", ContactNo: "9820104874" });
- $scope.count = $scope.Persons.length;
- }
- }
- });
- });
NOTE - Inside our Home controller we’ve defined a model named “count” with initial value set to zero.
- Inside our Index.cshtml file we made a provision for displaying the “controller count model value” inside a label control.
Now let’s try to run the application.
Figure 4: Detail 2
From the above snapshot we can see that the controller count model value is still zero while the custom directive count model value is 3 which is the length of the person array. So this states that the count model defined inside our custom directive is only accessible to the $scope object of our custom AngularJs directive and not to the controller $scope object.
Also to prove this more we can log both the $scope object and see whether the count model is different for the controller $scope object and for directive $scope object.
Figure 5: Scope
The above snapshot is self-explanatory.
Isolated Scope
In this both the $scope object (i.e. from Controller and from the Custom directive) will have their own isolated $scope object. Isolation means both the $scope object won’t be able to share/see any data of each other. For creating isolated scope we just need to set the $scope property of the custom directive to {}. Here's the updated code snippet for the same.
Home.js
- myApp.directive("contactInfo", function ()
- {
- return {
- restrict: "AE",
- templateUrl: '../../Directives/contactInfo.html',
- replace: false,
- scope: {},
- controller: function ($scope) {
- $scope.count = 0;
- $scope.Persons.push({ Name: "Shrikant Maharana", Address: "1324 Lions Street Andheri (W)", ContactNo: "9820104874" });
- $scope.count = $scope.Persons.length;
- console.info("Directive Scope:");
- console.log($scope);
- }
- }
- });
Let’s run the application and this time you’ll see the following output.
Figure 6: Output
Now we are getting an error message in the browser console stating that
“Cannot read property push of undefined”. This is because now our
controller $scope Person model is no longer accessible to the $scope object of the custom directive because of $scope isolation. But well there are ways through which you can inject a hole for this isolation so that you can access the model data of controller $scope inside the custom directive.
For more information about how to do that you can have a look at my article.
Creating Custom Directives In AngularJS - Part 2.