Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular expressions with Modernizr values?

I would like to show different controls if there is no html 5 native browser support for the new input types.

I was hoping to do something like this:

 <p ng-show="{{Modernizr.inputtypes.datetime-local}}">Modernizr says datetime-local is supported!</p>

However it appears that Modernizr is not available to Angular expressions.

Is the way to go about this to put all the Modernizr values I'm interested in on the rootscope on startup so they can be used in expressions or is there a better way?

like image 308
JohnC Avatar asked May 20 '14 20:05

JohnC


2 Answers

You can put all of Modernizr on the rootScope and it will work (note that Modernizr.inputtypes.datetime-local in ng-show should be Modernizr.inputtypes.datetimeLocal)...

app.run(function ($rootScope) {
    $rootScope.Modernizr = Modernizr;    
});

But my preference is to make it injectable using constant(), and expose just the required properties on the scope so the view is not coupled to Modernizr...

app.constant("Modernizr", Modernizr);

app.controller("controller", function ($scope, Modernizr) {
    $scope.browser = {
        supportsDateimeLocalInput: Modernizr.inputtypes.datetimeLocal,
        supportsEmailInput: Modernizr.inputtypes.email
    };    
});

And in the view...

<p ng-show="browser.supportsDatetimeLocalInput">
    Modernizr says datetime-local is supported!
</p>

JSFiddle

like image 52
Anthony Chu Avatar answered Nov 14 '22 20:11

Anthony Chu


First make sure you have Modernizr included in your project. I created a simple provider that will allow Modernizr to be injected into our directive rather than accessed globally. We use Modernizr to detect if we are on a touch device later on in the directive. http://joegaudet.com/angular/mobile/2013/07/22/fast-clicks-with-angular-js.html

angular.module('fast-click').provider('Modernizr', function () {
    'use strict';

    this.$get = function () {
        return Modernizr || {};
    };
});

Next let's define our fast click directive

angular.module('fast-click').directive('fastClick', function ($parse, Modernizr) {
    'use strict';

    return {
         restrict: 'A',
         link: function (scope, element, attrs) {
         }
    };
}); 

You'll notice we've injected two dependencies into our fast-click directive. The first is $parse, which converts the Angular expression that is passed to the directive into a function - this snippet is taken from the ng-click directive which ships with Angular, we wrap it in our own function for a bit of DRYness

clickFunction = function (event) {
    // if something has caused this handler to be
    // canceled lets prevent execution
    if (!canceled) {
        scope.$apply(function () {
            fn(scope, {$event: event});
        });
    }
};
like image 43
user3654728 Avatar answered Nov 14 '22 18:11

user3654728