Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right place to detect browser and show/hide a div

I want to show a div (using ng-if or ng-show/hide) if the user opens the page in a certain browser (in this case, chrome/chormium), and I'm not really sure where is the best place.

The javascript code looks like this: /chrome/i.test( navigator.userAgent ), but where is the best place to place it? In a filter? In a controller? In a directive?

like image 622
alexandernst Avatar asked Sep 09 '13 11:09

alexandernst


2 Answers

Check the below detailed browser detection script

http://www.quirksmode.org/js/detect.html

I will suggest you to use "Directive" or "Filter"

Working Demo

Below is the filter example code:

angular.module('myApp', []).filter('checkBrowser', function(){

    return function(){

        return /chrome/i.test(navigator.userAgent)
    }
})

Template Code:

<div ng-show="{{''|checkBrowser}}">Hello</div>
like image 132
JQuery Guru Avatar answered Oct 13 '22 06:10

JQuery Guru


You could assign your condition to a scoped variable inside the controller:

angular.module('myApp', []).controller('MyCtrl', ['$scope', function( $scope ) {
    $scope.isChrome = /chrome/i.test(navigator.userAgent);
});

Then inside your view:

<div data-ng-show="isChrome">You're running Chrome!</div>

If you need a variable that's available to any controller, use a Service:

angular.module('myApp', []).factory('UAService', function() {
    return {
        isChrome: /chrome/i.test(navigator.userAgent)
    };
});

Then from a page-level controller (i.e., one assigned to a top-level element such as <body>) or any other controller, inject your service:

angular.module('myApp', []).controller('MyCtrl', ['$scope', 'UAService', function( $scope, UAService ) {
    $scope.UAService = UAService;
});

Your service would now be accessible from any scope within the scope created by your page-level controller:

<div data-ng-show="UAService.isChrome">You're running Chrome!</div>
like image 30
André Dion Avatar answered Oct 13 '22 06:10

André Dion