0

I am looking to use a controller function as an element attribute like so:

<div ng-app='myApp'>
  <div ng-controller='myController as ctrl'>
    <div {{ ctrl.choose_attribute() }}></div>
  </div>
</div>

The choose_attribute function will return a string that matches one of many directives. However, my rendered html looks like this:

<div ng-app='myApp'>
  <div ng-controller='myController as ctrl'>
    <div }}='' ctrl.choose_attribute()='' {{=''></div>
  </div>
</div>

Am I approaching this the wrong way, or is there some trick to getting the return value to show up as an attribute?

Edit: It seems my choice of the word "attribute" was not that great, so here is an example directive that I am looking to create:

angular.module('myApp', [])
.controller('myController', function() {
  this.choose_attribute = function () {
    if (DataService.some_value == 'blah') {
      return 'content1';
    } else {
      return 'content2';
    }
  };
})
.directive('content1', function() {
  return {
    restrict: 'A',
    template: '<div>some content</div>'
  };
})
.directive('content2', function() {
  return {
    restrict: 'A',
    template: '<div>some other content</div>'
  };
});
wikenator
  • 310
  • 1
  • 4
  • 12

1 Answers1

0

Expressions will not be evaluated when placed as attribute names.

Will be evaluated: <div class="{{value}}">Text</div>

Will not be evaluated: <div {{value}}>Text</div>

What you need is a directive that takes a directive to add, adds it as an attribute to the element then compiles it.

Here is an example:

app.directive('addDirective', function($parse, $compile) {

  return {
    compile: function compile(tElement, tAttrs) {

      var directiveGetter = $parse(tAttrs.addDirective);

      return function postLink(scope, element) {

        element.removeAttr('add-directive');

        var directive = directiveGetter(scope);
        element.attr(directive, '');

        $compile(element)(scope);
      };
    }
  };
});

Usage:

<body ng-controller="MainCtrl as ctrl">
  <div add-directive="ctrl.choose_attribute()"></div>
  <div add-directive="ctrl.attribute"></div>
</body>

And JS:

app.controller('MainCtrl', function() {

  this.choose_attribute = function() {
    return 'content1';
  };

  this.attribute = 'content2';
});


app.directive('content1', function() {
  return {
    restrict: 'A',
    template: '<div>some content</div>'
  };
});

app.directive('content2', function() {
  return {
    restrict: 'A',
    template: '<div>some other content</div>'
  };
});

Demo: http://plnkr.co/edit/Kqdtb4wDYha9OebtVkEl?p=preview

tasseKATT
  • 38,470
  • 8
  • 84
  • 65