Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observe an expression from within a directive

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?

like image 861
MegaHit Avatar asked Dec 26 '12 01:12

MegaHit


1 Answers

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);
    }
like image 133
maxisam Avatar answered Nov 02 '22 23:11

maxisam