dman dman - 1 month ago 7
AngularJS Question

Directive template - use attribute for html text interpolation?

Angular 1.*

I am using a directive to make my code drier... or attempting to. But because of variances in the json data structure, I am not sure it's possible because of the interpolation text for each radio button.

<ppv-filter filter-name="Region" radio-value="choice.code"
sort="description" filter-data="regions"></ppv-filter>
<ppv-filter filter-name="Market" display-prop="description"
filter-data="markets"></ppv-filter>
<ppv-filter filter-name="Dealer" display-prop="code"
filter-data="dealers"></ppv-filter>


directive template:

<div ng-if="filterName === 'Region'">
<div ng-repeat="choice in filterData| orderBy: sort">
<input type="radio" value="{{choice.code}}" name="regionRadio">
{{choice.description}}
</div>
</div>

<div ng-if="filterName === 'Market'">
<div ng-repeat="choice in filterData| orderBy: 'code'">
<input type="radio" name="bob">
{{choice.code}}
</div>
</div>

<div ng-if="filterName === 'Dealer'">
<div ng-repeat="choice in filterData| orderBy">
<input type="radio" name="foo">
{{choice}}
</div>
</div>





angular.module('app')
.directive('ppvFilter', ['regionMarketDealerSrv',
function(regionMarketDealerSrv) {
return {
templateUrl: 'app/ppv/ppv-filter.dir.html',
restrict: 'E',
scope: {
filterName: '@',
sort: '@',
radioValue: '@',
filterData: '='
},


Is it possible to pass a attribute binding to take the place, for example, of
{{choice.description}}
? If not, then I am not really making my code drier by reusing a directive with so many code
ng-if
blocks.

Answer

I would create controller inside Your directive and inside it check properties sended to scope, in this particular example best would be switch statement. So in the switch set which param should be used in view.

( pseudo code in link or controller of directive )

switch (scope.filterName){

  case "Market":
  scope.field="code";
  break;


  //other possibilities
}

Next in view we need only one structure by using array syntax [field].

<div>
 <div ng-repeat="choice in filterData| orderBy: 'code'">
  <input type="radio" name="bob">
  {{choice[field]}}<!-- HERE MOST IMPORTANT -->
 </div>
</div>

I see that sorting also changes, so create second variable for sort type and assign it in the same switch in controller.


One more thing, directive attributes (props) assigned from parent scope can be used without any controller code, props are available in view, so it can be used in the same syntax like - {{someArr[filterName]}} where filterName was directive attribute.

Returning to Your problem - if we send by attribute name of property which should be used in view for example column:'@' and example value would be code,description then in view only {{choice[column]}} is needed.