What's the Angular Way to use Modernizer to conditionally load a placeholder polyfill?

4,008 views
Skip to first unread message

Jev Björsell

unread,
Apr 7, 2013, 3:32:31 PM4/7/13
to ang...@googlegroups.com
Hi All,

I need to use a placeholder polyfill in my app, if placeholder is not supported.

I'm using Modernizer to detect capabilities, and the jquery-placeholder polyfill.

In a simple html page, this logic would be appropriate;

    if (Modernizr.input.placeholder === false) {
        $('input, textarea').placeholder();

    }

What is the 'Angular Way' to check if placeholder is not supported, and then run the jquery polyfill?

My app has a log of input fileds, all using the placeholder attribute.

Thanks,
-Jev

Miguel Ping

unread,
Apr 8, 2013, 6:49:13 AM4/8/13
to ang...@googlegroups.com
I would say for you to use a directive to do that and apply it to each input. This way you get fine-grain control over which inputs you want to apply the shim.

<input ng-placeholder ..>

angular.module('...')
.directive('...', function(){
  return: {
     ...,
     link:  function(scope, element, attrs) {
      if(Modernizr.input.placeholder === false) {
        jQuery(element[0]).placeholder(); //element is a jqLite element, you have to unwrap it and "jquery" it

James Cook

unread,
May 24, 2013, 8:29:23 AM5/24/13
to ang...@googlegroups.com
A slight addition is to also name your directive "placeholder" so there will be no code changes to the html:

        <input type="email" x-ng-model="email" placeholder="Email" required>
        

    .directive( 'placeholder', ['$timeout', function ( $timeout ) {
        if ( Modernizr.input.placeholder === true ) return {};
        return {
            link : function ( scope, elm, attrs ) {
                if ( attrs.type === 'password' ) return;
                $timeout( function () {
                    $( elm ).val( attrs.placeholder ).focus(function () {
                        if ( $( this ).val() == $( this ).attr( 'placeholder' ) ) {
                            $( this ).val( '' );
                        }
                    } ).blur( function () {
                            if ( $( this ).val() == '' ) {
                                $( this ).val( $( this ).attr( 'placeholder' ) );
                            }
                        } );
                } );
            }
        };
    } ] )
Message has been deleted

Kumar Harsh Srivastava

unread,
Dec 15, 2013, 1:04:03 PM12/15/13
to ang...@googlegroups.com
No, you don't have to re-wrap the jqLite object into a jquery object. If jquery is available, angularjs automatically upgrades the jqlite DOM object to a full jquery object. Read more here.

Also, it's not required to have an "ng-placeholder" directive. You can just use the existing "placeholder" attribute, and write a directive to extend that.
Reply all
Reply to author
Forward
0 new messages