Switching AngularJS template
Our client wants a responsive website, but he wants to change and move so much content that we will face loading restrictions.
With bootstrap, you can show and hide blocks and move them with offset, but somehow it has limitations. This is a demanding client who will not comply with such restrictions, so we are looking for other options.
To avoid creating duplicate content and still be able to give a mobile / desktop experience, our team came up with AngularJS.
Our JSON controllers and Angular controllers can stay the same, but we only need to switch views if they are on mobile / tablet / desktop.
Is there a stable solution for the job? And can we test it as we test responsive design by resizing the browser, or is custom detection the only solution? This will be a pain during testing, as we need many devices or emulators to be tested.
source to share
You can create a custom directive for this.
app.directive('responsiveTemplate', function() {
return {
restrict: 'E',
template: '<ng-include src="template"></ng-include>',
scope: true,
link: function(scope, elem, attr) {
var mobile = attr.mobile;
var desktop = attr.desktop;
scope.template = desktop;
$(window).resize(function() {
if (windowSizeIsDesktop() && scope.template != desktop) {
scope.template = desktop;
scope.$apply();
}
else if (windowSizeIsMobile() && scope.template != mobile) {
scope.template = mobile;
scope.$apply();
}
});
}
}
})
Use as element
<responsive-template desktop="desktop.html" mobile="mobile.html"></responsive-template>
I have not defined functions windowSize
, although they are trivial to implement
source to share
I would probably just use ng-if to do this, but first I have to make sure you need it and can't just use css / media queries for what you are describing. Here is an example of ng-if logic:
<body ng-app="myApp">
<div ng-controller="ctrl" >
<div ng-if="isWide()">
<p>Wide Content</p>
</div>
<div ng-if="!isWide()">
<p>Narrow Content</p>
</div>
</div>
</body>
And js:
angular.module('myApp', []).controller('ctrl', function($scope, $window) {
$scope.isWide = function() {
return $window.innerWidth > 500; //your breakpoint here.
}
angular.element($window).on('resize', angular.bind($scope, $scope.$apply));
});
http://jsfiddle.net/gq2obdcq/8/
Just drag the section bar to see the results in the script.
source to share
$routeProvider.
when('/:menu/:page', {
controller:HandleCtrl,
template:'<div ng-include="templateUrl">Loading...</div>'
}).
In conjunction with:
function HandleCtrl($scope, $routeParams){
$scope.templateUrl = $routeParams.menu +'/'+ $routeParams.page + '.html'
}
Will it be safe? Inside the controller, I can decide which html file I want to use as a template
source to share