MrProgram
MrProgram

Reputation: 5242

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
}

Upvotes: 0

Views: 490

Answers (2)

The Reason
The Reason

Reputation: 7973

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

Upvotes: 2

Luka Jacobowitz
Luka Jacobowitz

Reputation: 23512

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.

Upvotes: 2

Related Questions