2014-09-12 15 views
0

我正在使用基於自舉開關的複選框開關(文檔位於:https://tictail.com/developers/documentation/uikit/#Switches)。ng-show無法使用複選框開關

我想用NG秀的元素,就像在這裏的例子:當我在交換機上單擊(選中複選框,綁開關) https://docs.angularjs.org/api/ng/directive/ngShow

但是什麼也沒有發生。

我使用的現有plunker把問題在正確的上下文: http://embed.plnkr.co/LRSGXqxjtbYcr6rjTj69/

HTML:

​​

謝謝!

+1

你想要展示和隱藏什麼?因爲我唯一能看到的是帶有標籤和複選框的字段集。 – user3811714 2014-09-12 09:59:02

+0

如果你正在談論contact/help中的複選框,它的工作正常。 – 2014-09-12 10:04:50

+0

你的花式開關根本就沒有開關,請看這裏http://plnkr.co/edit/VaqEOLhJMVa4jvCmqKx8?p=preview – sylwester 2014-09-12 10:18:06

回答

1

請記住,我很新的角度所以這可能不是最好的答案。

我想無論開關插件正在做的是防止複選框上的值被改變(或傳播到角度)。

我認爲你可以做的就是在你的指令上,將某些事情綁定到change事件上,並在指令中使用隔離範圍來與控制器中的變量進行雙向綁定。

HTML:

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

開關變量會做的指令

指令2路結合:

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

正是我在找的東西!感謝你的幫助。謝謝! – peta 2014-09-12 11:46:00

+0

似乎有時如果我點擊得非常快,它會「倒退」,所以即使開關設置爲「no」,ng-show也是如此。任何想法爲什麼會發生? – peta 2014-09-12 12:45:57

+0

另外我注意到,如果我設置複選框檢查加載像開關將設置爲「是」,但ng顯示將是假的,如果我綁定另一個常規復選框保留跟蹤交換機發生了什麼,它不會被檢查。所以它似乎只有當我點擊開關,而不是太快。 – peta 2014-09-12 12:51:26

2

你必須將你的代碼嵌套在ng-app中,以便它知道它是一個有角度的應用程序。

<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/

+0

'index.html'中有'ng-app ='myApp''第三行 – MiTa 2014-09-12 10:55:58