Building Pluggable Components in AngularJS: After yet Before
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-controller="OneCtrl">
<div pc-home></div>
<div pc-about></div>
<div pc-home></div>
</div>
<div class='header'>My Application</div>
CSS
div[ng-controller="OneCtrl"] {
background: gray;
width: 100px;
height: 100%;
position: absolute;
left: 0px;
bottom: 0px;
}
.header {
position: absolute;
left: 100px;
top: 0px;
right: 0px;
height: 50px;
background: pink;
text-align: center;
line-height: 50px;
font-size: 20px;
}
.home {
width: 80px;
margin: 10px 0 0 10px;
}
JavaScript
var App = angular.module('App', ['App.tools']);
angular.module('App.tools', ['tools.home']);
App.controller('OneCtrl', function($scope) {
});
App.factory('StateService', function() {
return {
openPanel: ''
};
});
// Separate module per feature
angular.module('tools.home', []).directive('pcHome', function($compile, StateService) {
return {
restrict: 'A',
replace: true,
scope: {},
controller: function($scope, $element, $attrs) {
$scope.stateService = StateService;
$scope.toggle = function() {
if (StateService.openPanel === 'home') {
StateService.openPanel = '';
} else {
StateService.openPanel = 'home';
}
};
},
template: '<button class="btn home" ng-click="toggle()" ng-class="{true: \'btn-primary\', false: \'btn-success\'}[stateService.openPanel == \'home\']">Home</button>',
link: function(scope, element, attrs) {
}
};
});