简体   繁体   中英

How to populate a HTML div on click event using Angularjs

What is the best way of populate a div (or ng-include) with a ready .html template using anuglarjs, not using ng-view and routing ?

for ex:

<div>
    <ng-include src="" />
</div>

<input type="button" ng-click="getTemplate()" value="Get template" />

$scope.getTemplate = function() {
   //Get and..populate template here
}

Use ng-if or ng-show :

<div ng-if="templateVisible">
    <ng-include src="" />
</div>

<input type="button" ng-click="getTemplate()" value="Get template" />

$scope.getTemplate = function() {
   $scope.templateVisible = true;
}

And using ng-show :

<div ng-show="templateVisible">
    <ng-include src="" />
</div>

<input type="button" ng-click="getTemplate()" value="Get template" />

$scope.getTemplate = function() {
   $scope.templateVisible = true;
}

The difference between the two is that ng-if doesn't populate the DOM, when the condition is false, while ng-show does, but marks it as display: none .

Using ng-show/ng-hide/ng-if

<div ng-controller="TodoCtrl">
  <div ng-show="show">Hello</div>
  <button ng-click="showHide()">Boom</button>
</div>



function TodoCtrl($scope) {
    $scope.show = true;
    $scope.showHide = function(){
      $scope.show = !$scope.show
    }
}

fiddle

Difference between ngShow/ngHide & ngIf - ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements, also ng-if creates a child scope while ng-show/ng-hide does not

Thanks

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM