Directives can be used to build reusable components. Here is an example of a "user box" component:
userBox.js
angular.module('simpleDirective', []).directive('userBox', function() {
return {
scope: {
username: '=username',
reputation: '=reputation'
},
templateUrl: '/path/to/app/directives/user-box.html'
};
});
Controller.js
var myApp = angular.module('myApp', ['simpleDirective']);
myApp.controller('Controller', function($scope) {
$scope.user = "John Doe";
$scope.rep = 1250;
$scope.user2 = "Andrew";
$scope.rep2 = 2850;
});
myPage.js
<html lang="en" ng-app="myApp">
<head>
<script src="/?originalUrl=https%3A%2F%2Friptutorial.com%2F%26quot%3B%2Fpath%2Fto%2Fapp%2Fangular.min.js%26quot%3B%26gt%3B%26lt%3B%2Fscript%26gt%3B%2520%2520%2520%2520%26lt%3Bscript%2520src%3D%26quot%3B%2Fpath%2Fto%2Fapp%2Fjs%2Fcontrollers%2FController.js%26quot%3B%26gt%3B%26lt%3B%2Fscript%26gt%3B%2520%2520%2520%2520%26lt%3Bscript%2520src%3D%26quot%3B%2Fpath%2Fto%2Fapp%2Fjs%2Fdirectives%2FuserBox.js%26quot%3B%26gt%3B%26lt%3B%2Fscript%26gt%3B%2520%2520%26lt%3B%2Fhead%26gt%3B%2520%2520%26lt%3Bbody%26gt%3B%2520%2520%2520%2520%2520%2520%26lt%3Bdiv%2520ng-controller%3D%26quot%3BController%26quot%3B%26gt%3B%2520%2520%2520%2520%2520%2520%2520%2520%26lt%3Buser-box%2520username%3D%26quot%3Buser%26quot%3B%2520reputation%3D%26quot%3Brep%26quot%3B%26gt%3B%26lt%3B%2Fuser-box%26gt%3B%2520%2520%2520%2520%2520%2520%2520%2520%26lt%3Buser-box%2520username%3D%26quot%3Buser2%26quot%3B%2520reputation%3D%26quot%3Brep2%26quot%3B%26gt%3B%26lt%3B%2Fuser-box%26gt%3B%2520%2520%2520%2520%26lt%3B%2Fdiv%26gt%3B%2520%2520%2520%2520%2520%2520%26lt%3B%2Fbody%26gt%3B%26lt%3B%2Fhtml%26gt%3B%253C%2Fcode">
user-box.html
<div>{{username}}</div>
<div>{{reputation}} reputation</div>
The result will be:
John Doe
1250 reputation
Andrew
2850 reputation