AngularJS Basic directive with template and an isolated scope


Example

Creating a custom directive with isolated scope will separate the scope inside the directive from the outside scope, in order to prevent our directive from accidentally change the data in the parent scope and restricting it from reading private data from the parent scope.

To create an isolated scope and still allow our custom directive to communicate with the outside scope, we can use the scope option that describe how to map the bindings of the directive's inner scope with the outside scope.

The actual bindings are made with extra attributes attached to the directive. The binding settings are defined with the scope option and an object with key-value pairs:

  • A key, which is corresponded to our directive's isolated scope property
  • A value, which tells Angular how do bind the directive inner scope to a matching attribute

Simple example of a directive with an isolated scope:

var ProgressBar = function() {
  return {
    scope: { // This is how we define an isolated scope
      current: '=', // Create a REQUIRED bidirectional binding by using the 'current' attribute
      full: '=?maxValue' // Create an OPTIONAL (Note the '?'): bidirectional binding using 'max-value' attribute to the `full` property in our directive isolated scope 
    }
    template: '<div class="progress-back">' +
              '  <div class="progress-bar"' +
              '       ng-style="{width: getProgress()}">' +
              '  </div>' + 
              '</div>',
    link: function(scope, el, attrs) {
      if (scope.full === undefined) {
        scope.full = 100;
      }
      scope.getProgress = function() {
        return (scope.current / scope.size * 100) + '%';
      }
    }
  }
}

ProgressBar.$inject = [];
angular.module('app').directive('progressBar', ProgressBar);

Example how to use this directive and bind data from the controller's scope to the directive's inner scope:

Controller:

angular.module('app').controller('myCtrl', function($scope) {
    $scope.currentProgressValue = 39;
    $scope.maxProgressBarValue = 50;
});

View:

<div ng-controller="myCtrl">
    <progress-bar current="currentProgressValue"></progress-bar>
    <progress-bar current="currentProgressValue" max-value="maxProgressBarValue"></progress-bar>
</div>