切换按钮指令的 AngularJS 列表 [英] AngularJS list of toggle buttons directive

查看:29
本文介绍了切换按钮指令的 AngularJS 列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可重复使用的切换/开关列表组件.

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

这是我的 工作 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?

推荐答案

在您的子指令中

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

在父控制器中:

this.toggles = [];
this.addToggle = function (toggle) {
  var rank = this.toggles.push(toggle);
  return rank;
};

这篇关于切换按钮指令的 AngularJS 列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆