0

I'm looking for an answer to this question:

Multi State button like toggle in angularJS

...but using a directive. The main reason being that I'm trying to achieve isolate scope in order to create a reusable button. I have tried:

angular.module('myApp', [])
    .directive('buttonToggle', function() {
        return {
            restrict: 'A',
            scope: {
                myBtnArr: "="
            },
            myBtnTxt: ["AND", "OR", "NOT"],
            template: '<button>{{ myBtnTxt[myBtnArr] }} </button>'
        }
    });

With something like this in the HTML:

<div button-toggle my-btn-arr=0></div>

But Angular doesn't seem to like any flavor of this, either showing the button but not the text or throwing the cryptic a.match is not a function error. Thoughts?

3
  • 1
    you have myBtnArr attribute wrong way..it should be hyphen separated like my-btn-arr="someVariable" where as someVariable will be scope variable, which hold value of 0 Commented Jan 7, 2016 at 22:40
  • You are correct but that's because I incorrectly transcribed the html, edited. Your solution seems to me like it would not create isolate scope? Commented Jan 7, 2016 at 22:46
  • If I do that then it's a string and not a number, which is what the "=" is meant to process. Commented Jan 7, 2016 at 23:23

1 Answer 1

1

You need to modify your directive to include a link function. Then place myBtnTxt on scope in there. Like so:

app.directive('buttonToggle', function() {
  return {
    restrict: 'A',
    scope: {
      myBtnArr: "="
      },
    template: '<button>{{myBtnTxt[myBtnArr]}}</button>',
    link: function(scope){
      scope.myBtnTxt = ["AND", "OR", "NOT"];
    }
  };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yep! Thanks jbrown!

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.