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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With