The right place to detect the browser and show / hide the div

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

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

+4
source share
2 answers

Check out the following detailed browser script definition

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

I suggest you use the "Directive" or "Filter"

Working demo

The following is an example filter code:

 angular.module('myApp', []).filter('checkBrowser', function(){ return function(){ return /chrome/i.test(navigator.userAgent) } }) 

Template Code:

 <div ng-show="{{''|checkBrowser}}">Hello</div> 
+2
source

You can assign your state to a variable with a scope inside the controller:

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

Then in your view:

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

If you need a variable accessible to any controller, use the Service:

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

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

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

Your service will now be accessible from any scope created by your page level controller:

 <div data-ng-show="UAService.isChrome">You're running Chrome!</div> 
+2
source

Source: https://habr.com/ru/post/1501283/


All Articles