Take the 2-minute tour ×

Basically, how can I listen to changes in an expression from within a directive?

I'm using the undocumented ng-required to conditionally require a certain field:

<input type="checkbox" ng-model="partner" checked />
<input ng-model="partnerName" placeholder="required" ng-required="partner" />

This works great (here's the Plunkr). The only problem with this is that it keeps the placeholder "required" text, regardless of whether it's actually required.

So, I decided to create my own directive. Here's how it should work:

<input ng-placeholder="{ 'required': partner }" />

The idea is similar to angular's ng-class, but I have no way how to accomplish this. Here's what I've got so far:

app.directive('ngPlaceholder', function ($parse) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            console.log( scope.$eval(attrs.ngPlaceholder) );

which logs a nice object that I can use to determine the placeholder value:

{ required: true }

but how do I then hook into the $digest/$apply cycle to update the placeholder attribute whenever partner changes?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Is this what you want ? plunker

the basic idea for your link function should be like

   link: function (scope, element, attrs) {
        scope.$watch(attrs.xngPlaceholder, function (newVal, oldVal, scope) {
          var att = '';
           angular.forEach(newVal, function (elm, key)
                att += elm ? (key + ' ') : ''; 
            element.attr('placeholder', att);
        }, true);
share|improve this answer
One suggestion: don't use ng- prefix since it's angulars, unless you know that in a future version they will implement ng-placeholder with the same syntax –  Liviu T. Dec 26 '12 at 8:33
Thanks ! That's true. However I just use original post's code. –  maxisam Dec 26 '12 at 14:38
add comment

An alternative approach, that does not require a directive:

placeholder="{{{true: 'required', false:''}[partner]}}"

The above creates object {true: 'required', false:''} and then indexes into the object using the current value of partner.

share|improve this answer
add comment

Your Answer


