Using controller with directive and isolating scope in AngularJs

AngularJS, a popular JavaScript framework, provides a feature called directives that allows developers to extend HTML with new attributes or elements. Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to “decorate” elements with behavior and manipulate DOM attributes in interesting ways. In this tutorial, we will delve deeper into the world of directives, exploring how to attach controllers to directives and isolate scopes within them.

Attaching a Controller to a Directive

Controllers in AngularJS are responsible for setting up the initial state of the scope object and adding behavior to it. They can be attached to directives to control their behavior and manage their data. Here’s how you can attach a controller to a directive:

var testApp = angular.module('testApp',[]);

testApp.directive('myDirective',function(){
  return {
    restrict:'E',
    template:'My Directive: {{displaytext}} : {{userinput}}',
    controller:function($scope){
      $scope.displaytext = 'Waiting for user to type';
      $scope.invoked = function(){
        $scope.displaytext = 'User Typed';
      }
    }
  }
});

In this example, the myDirective directive has a controller that defines a displaytext property and an invoked function on the scope. The invoked function is called when the user starts typing, updating the displaytext property.

Isolating Scopes in Directives

By default, a directive inherits the scope of its parent controller. However, sometimes you may want a directive to have its own isolated scope, especially when you want to reuse the directive across your application. Here’s how you can create an isolated scope in a directive:

testApp.directive('myDirective',function(){
  return {
    restrict:'E',
    scope:{}, // isolate scope
    template:'My Directive: {{displaytext}} : {{userinput}}',
    controller:function($scope){
      $scope.displaytext = 'Waiting for user to type';
      $scope.invoked = function(){
        $scope.displaytext = 'User Typed';
      }
    }
  }
});

In this example, the scope:{} line creates an isolated scope for the directive. Now, each instance of the directive has its own scope, and changes in one instance do not affect others.

Conclusion

Attaching controllers to directives and isolating scopes are advanced techniques that can make your AngularJS directives more powerful and reusable. By understanding these techniques, you can create more complex and modular AngularJS applications. In the next tutorial, we will explore how to dynamically attach controllers to a single directive. Stay tuned!

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts