bootstrap-switch與angularjs結合使用


bootstrap-switch和angularjs結合使用

由於angularjs的dom操作總是先執行,導致$(input[name="switch"])找不到元素,所以使用directive自定義指令,有兩種方法:

html部分:

 <my-input power="{{x.power}}" did="{{x.id}}"></my-input>

directive指令部分:

1、通過插入元素的方法

app.directive('myInput',function(factoryName){
   return{
       restrict : "AE",
       scope : {
           power  :"@",
           did : "@"
       },
       template :'<div class="switch"></div>',
       replace : true,
       link : function(scope,element,attr){
           var $input = $('<input type="checkbox" name="switch" checked>');
           $(element[0]).append($input);
           $(element[0]).children().bootstrapSwitch({
               'size':'small',
               onSwitchChange : function(target,state){
                  //state是開關的狀態
               }
           })
       }
   }
})

2、通過引入外部文件的方法

 1 return{
 2         template : '<div ng-include="getElement()"></div>',
 3         scope : {
 4             dtype : '@',
 5             id : '@'
 6         },
 7         replace : true,
 8         link : function(scope,element,attr){
 9             scope.getElement = function(){
10                 if(attr.dtype == 3){
11                     return 'testchecked.html';
12                 }else{
13                     return 'testunchecked.html';
14                 }
15             };
16         }
17     }

外部文件testchecked.html為

<div class="switch" data-on="info" data-off="success">
    <input type="checkbox" name="switch" checked/>
</div>
<script type="text/javascript">
    $("input[name='switch']").bootstrapSwitch({
        'size' : 'normal',
        'onColor':'info',
        'onSwitchChange':function(target,state){

        }
    })
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM