1

I am trying to create a directive that has an optional "label" for a button - if this label is not supplied, I want it to have a default value

this is the directive

angular.module('myApp')
  .directive('myButton',function(){

    var ctrl = function ($scope) {
        var controller = this;

        controller.label = controller.label || 'Save';

        console.log("label=",controller.label);
    };

    return {
        replace: true,
        restrict: 'E',

        scope: {
            label: '@?',
        },

        templateUrl: 'directives/myButton.html',

        controller: ctrl,
        controllerAs: 'controller',
        bindToController: true,
    };
});

the html in the template is this

<md-toolbar>
    <div class="md-toolbar-tools">
        <span flex></span>
        <md-button class="md-raised">{{controller.label}}</md-button>
    </div>
</md-toolbar>

and I am calling the directive like this

<my-button label="fooBar"></my-button>

this works - and I see the label "fooBar" on the button, and 'label=fooBar' on the console

however, if I don't supply the label

<my-button></my-button>

The button has no label, but I see 'label=Save' on the console

what am I missing ?

thanks

2
  • Seems to be working as expected in this plunker plnkr.co/edit/R7BmHJ3dGKU5Vz6s5T0H?p=preview I used template instead of templateUrl but not sure how that should change things. Commented Jul 11, 2015 at 10:10
  • yeah - it does - I can't understand why it doesn't work in my app. I've used the compile option (see accepted answer) and that did work though. Thanks for the help anyway. Commented Jul 11, 2015 at 13:03

1 Answer 1

1

You can use the compile method on the directive to achieve the desired result, a little example

.directive('my-bytton', [ function() {
    ...
    compile: function(element, attrs){
       if (!attrs.attrOne) { attrs.attrOne = 'default value'; }
       if (!attrs.attrTwo) { attrs.attrTwo = 'default value2'; }
    },
        ...
  }
});
Sign up to request clarification or add additional context in comments.

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.