Joe
Joe

Reputation: 551

How to add template page dynamically with dynamic values in it in angularjs

Actually I'm very new to angularJS so I'm asking some basic questions which may seem silly to you geeks. I am habituate of jQuery a bit much thats why some confusion is there as docs are also very limited.

    <!Doctype>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Example - example-example12-production</title>
      <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    </head>
    <body ng-app="docsTemplateUrlDirective">
      <div ng-controller="Controller as c">
      <button ng-click="c.showdiv()">show</button >
      <div id="d"></div>
    </div>
<script>

angular.module('docsTemplateUrlDirective', [])
  .controller('Controller', ['$scope', function($scope) {
this.showdiv=function(){

    //do the ajax call and get the value from server
    //pick the required template
    //render the returned value on picked template

}
}]);
</script>
    </body>
    </html> 

I want whenever I clicked and call showdiv() it should call ajax,get the value and render it in a template(say template.html) in div(id=d) section

Update: 1.say we have two button.if button1 is clicked then it will pick template1.html anf for button2 its template2.html.

2.ajax returns as {"Name":"AnyName","Age":"25"} like that in template1.html has binding as

<div>
{{Name}},{{Age}}
</div>

for button2 different value with different template style.

Upvotes: 0

Views: 204

Answers (1)

jeff carey
jeff carey

Reputation: 2373

Update your div "d" to say:

<div id="d" ng-include="chosenTemplate"></div>

Update buttons:

<button ng-click="c.showdiv('template1.html')">show 1</button >
<button ng-click="c.showdiv('template2.html')">show 2</button >

Then add something like the following:

this.showdiv = function(theTemplate) {

    $scope.chosenTemplate = theTemplate;

    // do AJAX call using $http.get
    $scope.Name = "John Smith";
    $scope.Age = 25;
}

Also note:

As mentioned above you can add the showdiv function to the scope so you won't have to prefix it with "c." in your html.

As I mentioned above you are missing a closing square bracket ] at the end of your controller definition.

Upvotes: 1

Related Questions