ng show不适用于复选框开关



我使用的是一个基于引导开关的复选框开关(此处的文档:https://tictail.com/developers/documentation/uikit/#Switches)。

我想在元素上使用ng-show,就像这里的例子一样:https://docs.angularjs.org/api/ng/directive/ngShow

但是,当我点击开关时,什么都不会发生(选中与开关相连的复选框)。

我用一个现有的plunker把这个问题放在正确的上下文中:http://embed.plnkr.co/LRSGXqxjtbYcr6rjTj69/

HTML:

 <fieldset>
  <legend>Test switch</legend>
  <div class="form-group">
    <label for="testSwitch">Test switch</label><br>
    <div class="switch" init-switch>
      <input type="checkbox" ng-model="testSwitch">
    </div>
  </div>
</fieldset>
<fieldset ng-show="testSwitch">
...

谢谢!

您必须将代码嵌套在ng应用程序中,以便它知道这是一个有角度的应用程序。

    <div ng-app="myApp">
        <fieldset>
            <legend>Test switch</legend>
            <div class="form-group" >
                <label for="testSwitch">Test switch</label><br>
                <div class="switch">
                    <input type="checkbox" ng-model="testSwitch"/>
                </div>
            </div>
        </fieldset>
        <h1 ng-show="testSwitch">Now you see me</h1>
    </div>

http://jsfiddle.net/df1gz8jk/1/

请记住,我是Angular的新手,所以这可能不是最好的答案。

我认为Switch插件所做的一切都是为了防止复选框上的值被更改(或传播到angular)。

我认为您可以在指令上执行操作,将某些内容绑定到更改事件,并在指令上使用隔离作用域来与来自控制器的变量进行双向绑定。

HTML:

<div class="switch" init-switch switch-variable="testSwitch">
   <input type="checkbox" id="check">
</div>

开关变量将与指令进行双向绑定

指令:

app.directive('initSwitch', function () {
        return {
            scope: {
              switchVariable: '=' //this is how you define 2way binding with whatever is passed on the switch-variable attribute
            },
            link: function (scope, element, attr) {
                scope.$evalAsync(function () {
                    element.switch();
                });
                element.on("change", function(){
                   if(scope.switchVariable)
                    scope.switchVariable = !scope.switchVariable
                   else
                    scope.switchVariable = true;
                   scope.$apply(); //I believe you need this to propagate the changes
                });
            }
        }
    });

编辑:

根据您的第一条评论,您可以尝试将指令事件更改为:吗

element.on("change", function(){
   if(element.children('.switch-off')[0]) //Looking for the class that determines to what side the switch is
     scope.switchVariable = false;
   else
     scope.switchVariable = true;
   scope.$apply(); //I believe you need this to propagate the changes
});

至于第二点,如果您将复选框设置为选中,那么您的链接功能需要知道复选框的状态:

scope.$evalAsync(function () {
  scope.switchVariable = element.children()[0].checked; //check if checkbox is checked (before the plugin changes the DOM
  element.switch(); //initialize the plugin
});

最新更新