问题描述
我想插入HTML的引导切换单选按钮()。引导交换机,这些已经在HTML工作时,我跑单选按钮
I'm trying to insert HTML for a Bootstrap Switch radio button (http://www.bootstrap-switch.org/) from an AngularJS controller using ngBind. Bootstrap Switch radio buttons that are already in the HTML work when I run
$('BS-开关。')bootstrapSwitch();
$('.bs-switch').bootstrapSwitch();
但单选按钮我插入通过ngBind的HTML保持简单的单选按钮。我认为这是一个时间问题。
But the radio button I insert into the HTML via ngBind stays a simple radio button. I think it's a timing issue.
例如:
HTML:
<!-- this doesn't get converted to a Bootstrap Switch radio button -->
<div ng-bind-html="exampleHTML"></div>
<!-- this does get converted -->
<input type="checkbox" class="bs-switch" name="my-checkbox2" checked>
控制器:
$scope.exampleHTML = $sce.trustAsHtml(
'<input type="checkbox" class="bs-switch" ' +
' name="my-checkbox1" checked>'
);
$('.bs-switch').bootstrapSwitch();
如果我做这样的事情在控制器下面,通过插入ngBind单选按钮被转换为引导开关 - 这就是为什么我认为这是一个计时问题:
If I do something like the following in the controller, the radio button inserted via ngBind gets converted to a Bootstrap Switch - this is why I think it's a timing issue:
$scope.exampleHTML = $sce.trustAsHtml(
'<input type="checkbox" class="bs-switch" ' +
' name="my-checkbox1" checked>'
);
setTimeout(function() {
$('.bs-switch').bootstrapSwitch();
}, 1000);
这是如何做到这一点(比使用超时一种更好的方式)的任何建议?我试图建立一个从JSON配置文件,这就是为什么我使用ngBind插入HTML程序生成一个动态的形式。
Any suggestion on how to do this (in a better way than using a timeout)? I'm trying to build a dynamic form that is generated programmatically from a JSON config file, which is why I'm using ngBind to insert HTML.
更新:
下面是一个
推荐答案
不要操作DOM内部控制,使用指令来代替:
Don't manipulate DOM inside controller, use directive instead:
<div ng-app="myApp">
<div ng-controller="myController">
<switch></switch>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope',
function($scope) {
}
]).directive('switch', function() {
return {
restrict: 'E',
'template': '<input type="checkbox" class="bs-switch" name="my-checkbox1" checked>',
'link': function(scope, element, attrs) {
$(element).find('input').bootstrapSwitch();
}
}
});
https://jsfiddle.net/nnkypoy9/23/
这篇关于AngularJS - ngBind和引导开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!