AngularJS list of toggle buttons directive

时光毁灭记忆、已成空白 提交于 2019-12-13 21:23:28

问题


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:


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;
};


来源:https://stackoverflow.com/questions/22620949/angularjs-list-of-toggle-buttons-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!