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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.