AngularJS Custom Directives - Isolate Scope Tutorial With Examples

Earlier we looked at different directive properties and created a simple directive using those properties. In this tutorial, we will discuss how to isolate the scope of directive using the scope property.

Isolate Scope

In AngularJS, directives have direct access to its parent by default. Therefore, we can only use it once within a given scope. If you want to make it reusable then we have to isolate it from the parent scope. We can use a directive’s scope property to isolate the scope.
This is a tricky topic and it may look a little complex when you see it first time but it’s a powerful feature in angularJS. Therefore, we are going to start from the basics and we will explore all the advanced features in the coming posts.

Why Isolate Scope

Before using the scope property, let’s see what happens if we are not using this property.
Let’s create directive named myEmployee directive to display a text input element. The ng-model directive binds the value entered in the text field and displayed inline.

In the following index.html file, we have used the myEmployee directive to display three input elements.

You will see the following output in your browser and enter some data in any of the fields. You can see that even if we change a single field, all of the fields get updated with the latest change. This is because they all share the same scope. This is why we need to isolate the scope of each directive.

Isolate Scope Example

We can isolate scope of the directive by adding a scope property to the directive. For now, we pass an empty object to the scope property to make it reusable. We will see the use of ‘@’, ‘&’ and ‘=’ with the scope property in the coming posts.

Type something in the below fields and you can see that the change in one of the fields does not affect the remaining. This is what is meant by isolating the scope.

I hope you got a better understanding on isolating the scope of directive. That’s all for now and we will see advanced isolate scope features in coming posts.

By admin

Leave a Reply