Javascript Can';当AngularJS使用ng开关时,是否附加divs?
当方法附加div时,我正在使用Javascript Can';当AngularJS使用ng开关时,是否附加divs?,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,当方法附加div时,我正在使用ng开关。这是创建的代码 <input type="checkbox" ng-model="data" /> <ng-switch on="data"> <span ng-switch-when="true"> <div class="firstSwitch"></div> </span> <span ng-switch-default> <di
ng开关。这是创建的代码
<input type="checkbox" ng-model="data" />
<ng-switch on="data">
<span ng-switch-when="true">
<div class="firstSwitch"></div>
</span>
<span ng-switch-default>
<div class="secondSwitch"></div>
</span>
</ng-switch>
在这里,文本正确地附加在firstSwitch
div中,因为它最初是创建的,但是文本没有附加在secondSwitch
div中,因为它没有创建
所以,我不能在那个div中追加。所以,如何克服这个问题。这是你的建议试试这个
<div class="secondSwitch"><div id="replacediv"></div></div>
var divElement = angular.element(document.querySelector('#replacediv'));
var appendHtml = $compile('<div>test</div>')($scope);
divElement.append(appendHtml);
var divElement=angular.element(document.querySelector('#replacediv');
var appendHtml=$compile($test')($scope);
追加(appendHtml);
正如您已经注意到的,ng switch修改DOM,而firstSwitch最初并没有创建。您应该使用绑定来实现这一点。这里有工作
更新
和绑定到html的演示您可以使用ng show
指令
//代码在这里
var app=angular.module('plunker',[]);
app.controller('MainCtrl',函数($scope,$timeout){
$scope.data=false;
$scope.show=false;
$scope.change=函数(){
$timeout(函数(){
$scope.show=!$scope.show;
},300);
}
});代码>
检查
显示第一个开关
显示第二个开关
对于文本,其工作正常。但是如果我想在里面添加一个div呢?添加了链接到demo并绑定到htmlIs这就是你想要的吗?是的。但是我想从纯javascript中附加div。我们可以这样做吗?只有在DOM中存在父元素时才能这样做。用例是什么?我们正在努力实现什么?
<div class="secondSwitch"><div id="replacediv"></div></div>
var divElement = angular.element(document.querySelector('#replacediv'));
var appendHtml = $compile('<div>test</div>')($scope);
divElement.append(appendHtml);
<ng-switch on="data">
<span ng-switch-when="true">
<div class="firstSwitch"><p>{{firstText}}<p></div>
</span>
<span ng-switch-default>
<div class="secondSwitch"><p>{{secondText}}<p></div>
</span>
app.controller('MainCtrl', function($scope, $timeout) {
$scope.data = false;
$timeout(function(){
$scope.firstText = "First Switch is displayed";
$scope.secondText = "Second Switch is displayed";
},100);