I am using ng-switch when
method to append divs. This is the code created
<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>
Its working fine now. But when i want to append something in the div.
Say, i want to append text using javascript inside secondSwitch
div, but i can't append it because initially the secondSwitch
div is not appended.
setTimeout(function(){
$(".secondSwitch").html("<p>Second Switch is displayed</p>");
$(".firstSwitch").html("<p>First Switch is displayed</p>");
},100);
Here the text is appended properly inside firstSwitch
div because initially it is created but the text is not appended inside secondSwitch
div because it's not created.
So, i can't append inside that div. So, how to overcome this problem guys. Here is the Plnkr
As you already noticed ng-switch modifies DOM and firstSwitch is not created initially. You should use binding to get this working. Here is working demo
<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);
Update
And here's demo for binding to html
Try this
<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);
you can use ng-show
directive for this.
// Code goes here var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope,$timeout) { $scope.data = false; $scope.show = false; $scope.change = function(){ $timeout(function(){ $scope.show = !$scope.show; },300); } });
<script src="http://code.jquery.com/jquery-1.12.2.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="plunker"> <div ng-controller="MainCtrl"> <input type="checkbox" ng-model="data" ng-change="change()" /> Check <ng-switch on="data"> <span ng-switch-when="true"> <div class="firstSwitch"> <p ng-show="show">First Switch is displayed</p> </div> </span> <span ng-switch-default> <div class="secondSwitch"> <p ng-show="!show">Second Switch is displayed</p> </div> </span> </ng-switch> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.