AngularJS: Include custom module in AngularJS

Hi Guys,

You can add custom module in your current module by using dependency injection.

In the example below parent module inject ngTable module which is custom defined or any third party implementation.
var app = angular.module('simpleDirective', ['ngTable']);

Below, I tried to explain how you can separate parent module directive in a separate module which can be reused in any other project.

You can find implementation code below.
index.html
<html ng-app="simpleDirective">
<head>
<script src="angular.min.js"></script>
<script src="app.js"></script>
<script src="ngTable.js"></script>
</head>
<body>
<div ng-controller="Controller">
  <h1>Table created by simpleDirective module</h1>
  <my-customer info="customer"></my-customer>
  <h1>Table created by ngTable module</h1>
  <ng-table-direcitve info="customer"></ng-table-direcitve>
</div>
</body>
</html>
app.js
var app = angular.module('simpleDirective', ['ngTable']);

app.controller('Controller', ['$scope', function($scope) {
  $scope.customer = [{
    name: 'Alex',
    quantity: '70'
  },{
    name: 'Alisha',
    quantity: '100'
  },{
    name: 'Shankar',
    quantity: '50'
  }];
}]);

app.directive('myCustomer', function() {
  return {
   restrict:"E",
   scope:{
    customerInfo:"=info"
   },
   templateUrl: "table.html"
  };
});
ngTable.js
var tableModule = angular.module("ngTable",[]);

tableModule.directive("ngTableDirecitve", function(){
 return {
  restrict:"E",
  scope:{
   customerInfo:"=info"
  },
  templateUrl: "table.html"
 }
});
table.html
<table ng-repeat="obj in customerInfo">
 <tr>
  <td>
   {{obj.name}}
  </td>
  <td>
   {{obj.quantity}}
  </td>
 </tr>
</table>


Good Day :)

Post a Comment

0 Comments