切换按钮的指令

帕库拉鲁·丹尼尔(Pacuraru Daniel)

我正在尝试创建一个指令来创建“是/否”切换按钮。现在我什至不知道我的HTML布局是否还可以,但是到目前为止,我做到了:

<div class="toggle" toggle-button"><input type="checkbox" ng-model="confirms" /></div>
<div class="toggle" toggle-button"><input type="checkbox" ng-model="listresults" /></div>

那是应该添加到UI中的HTML,以便以后可以在控制器中使用该模型。实际上,我有一个设置页面,其中有很多YES / NO按钮,例如本示例。

我想要的工作方式是当指令将按钮初始化时,它应根据每个ng模型的值将按钮显示为红色或绿色(如果confirms = false,则按钮应为红色,如果listresults为true,第二个按钮应为绿色)。现在,当我按下按钮时,它应该将ng-model的值从false更改为true或反之,并应该在toggle类附近添加或删除“ on”类,以便我可以在其中进行设计。

我的完整HTML for按钮应如下所示:

<div class="toggle" toggle-button>
    <input type="checkbox" ng-model="listresults" />
    <div class="toggle-inner">
        <div class="toggle-inner-yes"></div>
        <div class="toggle-inner-no"></div>
    </div>
</div>

到目前为止,我已经做到了,我不确定我的方法是否正确,如果您有更好的主意,请告诉我。

myApp.directive('toggleButton', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attr) {

            // add elem
            var html = angular.element('<div class="toggled"><div class="on"></div><div class="off"></div></div>');
            elem.append(html);

            elem.bind('click', function() {
                alert('a');
            });
        }
    }
});

现在,我只是在按钮内添加了HTML的其余部分,并添加了click事件,但我不知道如何从输入到指令中获取每个ng-model的值,更不用说将ng-model从true更改为false并在按钮上添加或删除“ on”类。

感谢您对此的任何帮助或建议。

瓦迪姆

您可以尝试以下操作:http : //plnkr.co/edit/yRWumtd7RwLksFowBRmc?p=preview

通过属性将模型传递给指令。使用'='指令范围定义中的值对传递的属性进行双向绑定在指令内部,使用ng-class指令在切换按钮上切换类。使用ng-click可切换的数据为界外控制的范围。

的HTML

<div ng-controller="ctrl">
  <div toggle="item" ng-repeat="item in items"></div>
</div>

的JavaScript

angular.module('app',[]).
  controller('ctrl', ['$scope', function($scope) {
    $scope.items = [{
      text: 'Setting 1',
      checked: false
    }, {
      text: 'Setting 2',
      checked: false
    }, {
      text: 'Setting 3',
      checked: false
    }]
  }]).
  directive('toggle', function() {
    return {
      scope: {
        toggle: '='
      },
      template: '<div ng-click="toggle.checked=!toggle.checked" ng-class="{\'toggle\':true, \'toggle-inner-yes\':toggle.checked, \'toggle-inner-no\':!toggle.checked}">{{toggle.text}}</div>',
      replace: true
    }
  });

的CSS

.toggle {
  border: 1px solid silver;
  display: inline-block;
  margin: 0.5em;
  padding: 0.5em;
  color: white;
}

.toggle-inner-yes {
  background-color: green;
}

.toggle-inner-no {
  background-color: red;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章