Question

I've looked around, found several resources labeled 'ng-placeholder' or something incredibly similar. I cannot get this to work:

<input type="text" placeholder="{{option.name}}" class="form-control" ng-switch-when="text" />

I've noticed there doesn't appear to be anything on the input documentation as well. I'm pretty new to angular, and this has done nothing but frustrate me for a few hours. There must be a way to do this.

Was it helpful?

Solution

Why not write your own directive for ng-placeholder? Something simple like this should work. You can call it in your html like this

<input ng-placeholder='test'>

Where test is a scope variable in the current controller.

.directive('ngPlaceholder', function($document) {
  return {
    restrict: 'A',
    scope: {
      placeholder: '=ngPlaceholder'
    },
    link: function(scope, elem, attr) {
      scope.$watch('placeholder',function() {
        elem[0].placeholder = scope.placeholder;
      });
    }
  }
});

OTHER TIPS

There exists a conditional attribute property in AngularJS ng-attr-{property_name}

For example, I'm using different placeholders for different search terms using

 ng-attr-placeholder="{{isAdvanceSearch ? setPlaceholder(searchOption) : 'John Smith, 08/23/1970, 123'}}"

Here on the basis of isAdvanceSearch variable, I'm setting different placeholders in setPlaceholder method.

setPlaceholder method returns the placeholder to set in the input field.

$scope.setPlaceholder = function(searchOption) {
     if (searchOption === "foo") {
          return "Search by foo… e.g. foo1";
     } else if (searchOption === "bar") {
          return "Search by bar… e.g. bar123";
     } else {
          return "John Smith, 08/23/1970, 123";
     }
};

Note: John Smith, 08/23/1970, 123 is the default placeholder. Don't forget to wrap the expression in the {{}} brackets.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top