Observe the expression from the directive

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


I use undocumented ng-required to conditionally request a specific field:

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

This works fine ( here is Plunkr ). The only problem is that it saves the text placeholder "required", regardless of whether it is really needed.


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 ng-class , but I have no way to achieve it. Here is what I have so far:

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

which registers a good object that I can use to determine the value of placeholder :

 { required: true } 

but how do I then connect to the $digest / $apply loop to update the placeholder attribute when partner changes?

+6
source share
2 answers

Is this what you want? plunker

The basic idea of ​​your link function should be similar to

  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); } 
+2
source

An alternative approach that does not require a directive:

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

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

0
source

All Articles