Building Pluggable Components in AngularJS: After
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<div ng-app="App">
<div ng-controller="MyCtrl">
<div my-menu></div>
</div>
</div>
<div class='header'>My Application</div>
<script type="text/ng-template" id="menu.tpl.html">
<div class='menu-template' ng-show="menuService.openPanel == 'menu1'">
<ul>
<li ng-repeat="choice in choices" ng-bind-template="{{$index + 1}}. {{choice}}"></li>
</ul>
</div>
</script>
CSS
div[ng-controller="MyCtrl"] {
background: gray;
width: 100px;
height: 100%;
position: absolute;
left: 0px;
bottom: 0px;
}
.header {
position: absolute;
left: 100px;
top: 0px;
right: 0px;
height: 50px;
background: grey;
text-align: center;
line-height: 50px;
font-size: 20px;
}
.menu {
width: 80px;
margin: 10px 0 0 10px;
}
.menu-template {
position: absolute;
background: rgb(40, 96, 117);
left: 100px;
top: 50px;
bottom: 0px;
right: 0px;
padding: 20px;
overflow: auto;
color: white;
}
JavaScript
var App = angular.module('App', ['tools']);
//angular.module('App.tools', ['tools.menu']);
App.controller('MyCtrl', function($scope, MenuService) {
MenuService.openPanel = 'menu1';
});
App.factory('MenuService', function() {
return {
openPanel: ''
};
});
// Separate module per feature
angular.module('tools', []).directive('myMenu', function($compile, MenuService) {
return {
restrict: 'A',
replace: true,
scope: {},
controller: function($scope, $element, $attrs) {
$scope.menuService = MenuService;
$scope.toggle = function() {
if (MenuService.openPanel === 'menu1') {
MenuService.openPanel = '';
} else {
MenuService.openPanel = 'menu1';
}
};
$scope.choices = [
'Share whats new...',
'You may know',
'Updates from followers',
'Few posts from communities',
'Scrolling now for more updates',
'Loading... :-)'
];
},
template: '<button class="btn menu" ng-click="toggle()" ng-class="{true: \'btn-primary\', false: \'btn-success\'}[menuService.openPanel == \'menu1\']">Menu</button>',
link: function(scope, element, attrs) {
angular.element(document.getElementsByTagName('body')).append(
$compile('<div ng-include="\'menu.tpl.html\'"></div>')(scope)
);
}
};
});