当使用ng-switch-AngularJS时,无法附加div?

时间:2016-06-15 06:29:54

标签: javascript jquery angularjs

我使用ng-switch when方法追加div。这是创建的代码

<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>

现在工作正常。但是当我想在div中附加一些东西时。

说,我想在secondSwitch div中使用javascript附加文本,但是我无法附加它,因为最初没有附加secondSwitch div。

setTimeout(function(){
    $(".secondSwitch").html("<p>Second Switch is displayed</p>");

    $(".firstSwitch").html("<p>First Switch is displayed</p>");
},100);

此处文本在firstSwitch div内正确附加,因为最初它已创建,但文本未附加在secondSwitch div中,因为它未被创建。

所以,我不能追加到那个div里面。那么,如何克服这个问题呢。这是Plnkr

3 个答案:

答案 0 :(得分:2)

正如您已经注意到ng-switch修改DOM并且最初未创建firstSwitch。您应该使用绑定来实现此功能。这是工作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);

<强>更新
here's演示用于绑定到html

答案 1 :(得分:0)

试试这个

<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);

答案 2 :(得分:0)

你可以使用ng-show指令。

&#13;
&#13;
// 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);
   }
});
&#13;
<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>
&#13;
&#13;
&#13;