In my last post we had learned the basics of creating a custom directive in angular js.
In this post we will learn how we can attach a controller to a directive and also to isolate scopes in directives.
If you are just getting started on directives and have no idea what I’ve said in the above lines ,please visit my previous tutorial to understand the basics of custom directives in angular js, here.
View demo: here
Download Code: here
Attaching a controller to a directive.
Lets build on our code from last tutorial.
var testApp = angular.module('testApp',[]);
testApp.directive('myDirective',function(){
return {
restrict:'E',
template:'
Lets add a controller to our directive.
testApp.directive('myDirective',function(){
return {
restrict:'E',
template:'
+'
{{displaytext}} : {{userinput}}
',
controller:function($scope){
$scope.displaytext = 'Waiting for user to type';
$scope.invoked = function(){ //Will call this function on change and update the value of displaytext variable.
$scope.displaytext = 'User Typed';
}
}
}
});
Here above, we have added a controller to the directive,it contains a function $scope.invoked() which updates the value of $scope.displaytext when the user starts typing.We have called this function using ng-change directive of angular js.
Isolating Scopes in directive.
Isolated scopes are complex to understand , you can read about it for days and still be unable to crack the shell.
Here I will explain you the basic of how to use isolated scopes and why would it be useful.
Lets take the above directive and use it twice on the same page.
Example:
Without Isolated scope
Start typing and notice the model in both the places is updated.
Please check out the left section in this demo for better understanding.
Start typing in any text box you will notice the directive takes the same scope value at both places.
We do not want that to happen, we want our directive to work independently,regardless of where it is used and how many times it is used.
Now let me tweak the code in the js file a little bit.
testApp.directive('myDirective',function(){
return {
restrict:'E',
scope:{}, //isolate scope
template:'
+'
{{displaytext}} : {{userinput}}
',
controller:function($scope){
$scope.displaytext = 'Waiting for user to type';
$scope.invoked = function(){ //Will call this function on change and update the value of displaytext variable.
$scope.displaytext = 'User Typed';
}
}
}
});
Please check out the right section in this demo for better understanding.
Here scope:{} specifies that the directive has an isolated scope , yes that’s it , just one line and now you have a directive with an isolated scope.
Now when you type in any text box on the right the model value of the other one is not updated.
There are more things to isolated scopes , but right now we will limit to just this.
You can download the code here .
In my further tutorial we will be learning the trick to dynamically attach controllers to a single directive.