bootstrap-switch与angularjs结合使用

bootstrap-switch和angularjs结合使用

由于angularjs的dom操作总是先执行,导致$(input[name="switch"])找不到元素,所以使用directive自定义指令,有两种方法:

html部分:

 <my-input power="{{x.power}}" d></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>