How to create reusable templates as components in angularjs using custom directive?

4.16K viewsProgrammingangularjs javascript programming
0

How to create reusable templates as components in angular 1 using custom directive?

Answered question
0

One can create custom angularjs directive to achieve the same. The idea is to segregate different reusable HTML templates (components) and use them as and when needed.
JS for the same

reusableComponents = angular.module("reusableComponents", []);
 reusableComponents.directive('myComponent', function() {
 return {
  scope:{
   attrib1: '@', // @ is used for assigning string values
   attrib2: '@',
   clickFunction: '=' // = is used for assigning objects
                        // more attributes here if needed
  },
  restrict: 'E',
  templateUrl: 'components/component.html',		
  controller: function($scope){
   $scope.attrib1 = attrib1;
   $scope.attrib2 = attrib2;
   $scope.clickFunction = clickFunction;
   // more attributes here if needed
  }
 }
});


Below is the markup of how this can be effectively used:

<my-component attrib1='value1' attrib2='value2' ng-click='clickFunction()'> 
</my-component>

Edited answer
Write your answer.

Categories