Skip to content

Instantly share code, notes, and snippets.

@singhmohancs
Last active March 3, 2017 18:18
Show Gist options
  • Save singhmohancs/2c3d67b6ceddb9879c1d6b6194d8b21c to your computer and use it in GitHub Desktop.
Save singhmohancs/2c3d67b6ceddb9879c1d6b6194d8b21c to your computer and use it in GitHub Desktop.
Determine device type from container width
/**
* @ngdoc Directive
* @name app.directive.detectViewPort
* @module app
*
* @description
* detectViewPort staring component with star
* @TODO
* onDetectViewPort callback
* @author Mohan Singh ( gmail::mslogicmaster@gmail.com, skype :: mohan.singh42 )
*/
(function () {
'use strict';
angular
.module('app')
.directive('detectViewPort', ['$detectViewPort', function ($detectViewPort) {
return {
restrict: 'A',
template: '',
scope: {
onDetectViewPort: '&?',
},
link: function (scope, element, attributes) {
var viewPortWidth = angular.element(element).parent()[0].clientWidth;
$detectViewPort.setViewPortWidth(viewPortWidth);
}
};
}])
.service('$detectViewPort', [function () {
var $this = this;
$this.deviceType = '';
$this.setViewPortWidth = function (viewPortWidth) {
$this.viewPortWidth = viewPortWidth;
determineDevice();
};
function determineDevice() {
if ($this.viewPortWidth < 768) {
$this.deviceType = 'xs';
} else if ($this.viewPortWidth >= 768 && $this.viewPortWidth < 992) {
$this.deviceType = 'sm';
} else if ($this.viewPortWidth >= 992 && $this.viewPortWidth < 1200) {
$this.deviceType = 'md';
} else if ($this.viewPortWidth >= 1200) {
$this.deviceType = 'lg';
}
}
}])
})();
@singhmohancs
Copy link
Author

How to use

Step 1. Any Controller

app.controller('AnyController', ['$detectViewPort','$scope', function($detectViewPort, $scope){
   $scope.$detectViewPort = $detectViewPort; //  $scope.$detectViewPort - You can name it anything E.g. $scope.device
}]);

Step 2. Angular View(Template)

<body>
  <div class="container-div" detect-view-port>
    <div data-ng-class="{'col-sm-6' :   $scope.$detectViewPort !== 'xs'}"></div>
     <div data-ng-class="{'col-sm-6' :   $scope.$detectViewPort !== 'xs'}"></div>
  </div>
</body>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment