问题
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