Ievgen
Ievgen

Reputation: 8086

How to use transclude without template in Angular directive?

<button command="saveCmd">{{saveText}}</button>

Command directive does not have any template - it's behavioral directive. But I need to use transclude: true to display {{saveText}}.

I could create dummy template like template: "<div ng-transclude></div>" but I'm not sure if div inside button is valid html for all browsers.

Also I could use an attribute to define title, for example <button title="saveText"... But my question is about ng-transclude without template. Is it possible?

Thanks in advance.

Update:

A new 'isolate' scope scope: {} inside directive is a reason why {{saveText}} is not persisted by default.

Upvotes: 4

Views: 2911

Answers (1)

Jaap
Jaap

Reputation: 3220

You can make a directive without a controller, and without an isolated scope. In the link function I sometimes do things like this:

.directive('toggle', function ($parse) {
  return {
    /* We can't use an isolated scope in this directive, because it happens 
     * all the time that you need to put a toggle on an element that uses the scope:
     * <span toggle="boolVar" ng-class="{active: boolVar}">{{someVar}}</span>
     *
     * Transclusion can be an option to make the {{someVar}} work, 
     * but the ng-class will use the isolated scope for this directive
     * (if we'd use the isolated scope, which we don't)
     */
    link: function (scope, $element, attrs) {
      // use a $parse getter/setter, because toggle can contain a
      // complicated expression
      var getter = $parse(attrs.toggle);
      var setter = getter.assign;

      $element.on('click', function () {
        scope.$apply(function () {
          setter(scope, !getter(scope));
        });
      });
    }
  };
});

Maybe this $parse trick helps with your command set up...

Upvotes: 1

Related Questions