Nested angular directives
by daslashi
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<opening-hours button-size="small"></opening-hours>
JavaScript
var app = angular.module('myApp', []);
app.directive('openingHours', function () {
return {
restrict: 'E',
template: '<button type="button" class="btn btn-info btn-xs" responsive-button button-size="{{ buttonSize }}">Show Opening Hours</button>',
link: function (scope, element, attrs) {
scope.buttonSize = attrs.buttonSize;
}
};
});
app.directive('responsiveButton', function ($window) {
return function (scope, element, attrs) {
var handleMediaMatch = function (mql) {
var smallButtonWidth = 170;
var standartButtonWidth = 250;
if (mql.matches) {
element.removeClass('btn-xs');
element.addClass('btn-block');
element.removeAttr('style');
} else {
element.removeClass('btn-block');
if (attrs.buttonSize == 'small') {
element.addClass('btn-xs');
element.css('min-width', smallButtonWidth + 'px');
} else {
element.css('min-width', standartButtonWidth + 'px');
}
}
};
var mobileMaxWidth = 640;
scope.$watch(attrs.buttonSize, function () {
var mql = $window.matchMedia('(max-width: ' + mobileMaxWidth + 'px)');
mql.addListener(handleMediaMatch);
handleMediaMatch(mql);
});
}
});