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?
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) {
          element.removeAttr('placeholder');
          var att = '';
           angular.forEach(newVal, function (elm, key)
                att += elm ? (key + ' ') : ''; 
            });
            element.attr('placeholder', att);
        }, true);
    }
                        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