0

I'm writing a directive and I'd like to have an attribute that can accept an expression, template url or string. Is there an angular method I can use that will resolve such a parameter? I mean where I can do....

<directive dialog="path/to/template.htm"></dialog>

or

<directive dialog="Are you sure you want to do that?" type="confirm"></dialog>

And in my directive code all I need to do is something like...

directive('dialog', function ($http) {
    return {
        compile: function (element, attrs) {
            var dialogContent = angular.resolveExpression(attrs.dialog);
        }
    }
}).

The idea being that if template.htm contained expressions within it or directives that they would all be parsed correctly.

Ben
  • 60,438
  • 111
  • 314
  • 488

2 Answers2

2

You should use attribute $observe to achieve it, you would even get updates when attribute gets changed:

app.directive('test', function() {
  return {
    link: function(scope, elm, attr) {
      attr.$observe('dialog', function(value) {
        // this function will run everytime the attribute evaluate to
        // a different value, and "value" will be the already interpolated
        // string.
      });
    }
  };
});

Here is a working Plnker.

Caio Cunha
  • 23,326
  • 6
  • 78
  • 74
1

The proper way to do it is to use the & scope option...

directive('slideToggle', function () {
        return {
            replace: true,
            restrict: 'E',
            scope: {
                on: '&',
                off: '&',
                bindto: '='
            },
            template: '<input type="checkbox" name=""/>',
            link: function (scope, element, attrs) {
                $(element).iButton({
                    labelOn: attrs.onlabel,
                    labelOff: attrs.offlabel,
                    enableDrag: (attrs.draggable == "false") ? false : true,
                    change: function () {
                        if (scope.bindto) {
                            scope.bindto = false;
                            scope.on();
                        } else {
                            scope.bindto = true;
                            scope.off();
                        }
                        scope.$apply();
                    }
                });
            }
        }
    })

Then in my HTML:

<slide-toggle onLabel="Active" offLabel="Inactive" bindTo="workstation.active" off="makeInactive()" on="makeActive()"></slide-toggle>
Ben
  • 60,438
  • 111
  • 314
  • 488