AngularJS list of toggle buttons directive

2019-09-01 01:46发布

I wanted to create a reusable component of toggles/switches list.

I've already made a <toggle> directive, and now want a <toggle-list> containing multiple <toggle>'s.

<toggle-list>
  <toggle value="A">Toggle A</toggle>
  <toggle value="B">Toggle B</toggle>
</toggle-list>

.

app.directive("toggle", function(){
return {
    scope: {},
    restrict: "E",
    transclude:true,
    templateUrl: "toggle-element.html", 
    link: function(scope){
      scope.toggled = false;

      scope.toggle = function(){
        scope.toggled = !scope.toggled;
      }
    }
}
});

Here's my working plnkr.

I want my <toggle-list> to return eg. array of values that are selected.
How do I implement this?
Is it even a good way of doing this, or am I just trying to reinvent the wheel?

1条回答
可以哭但决不认输i
2楼-- · 2019-09-01 01:53

in your child directive

require: '^toggleList',

now you have access to togglelist via the fourth parameter of the link function.

function(scope, el, attrs, toggleListCtrl, $transclude)

then you could call a method on the parent controller

from the toggle directive fill an array with the child elements :

scope.rank = toggleListCtrl.addToggle(el);

in the parent controller:

this.toggles = [];
this.addToggle = function (toggle) {
  var rank = this.toggles.push(toggle);
  return rank;
};
查看更多
登录 后发表回答