Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17784

Rendering Angularjs Template from within controller

Suppose I have following angularjs template

<script type="text/ng-template" id="tmp">
<li>    
{{firstname}} {{lastname}}</li>
</script>

and I have two textboxes and a save button like

<input name="firstname" type="text"/>
<input name="lastname" type="text"/>
<button name="save" text="save"/>

when user enters values in firstname and lastname textboxes and press on save button I want these two values to be passed to the template and resultant html should be appended to an existing ul. How can I do it with angular?

Upvotes: 1

Views: 999

Answers (1)

bmceldowney
bmceldowney

Reputation: 2305

You could create a directive to dynamically compile your template and append it to the ul when someone hits the save button, but that's basically the whole purpose of ng-repeat.

Here's how it can work with an ng-repeat instead:

angular.module('main', []);

angular.module('main').controller('MainCtrl', function ($scope) {
	$scope.names = [];
  
	$scope.save = function () {
		$scope.names.push({first: $scope.firstname, last: $scope.lastname});
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="main" ng-controller='MainCtrl'>

  <input name="firstname" type="text" ng-model='firstname'/>
  <input name="lastname" type="text"ng-model='lastname'/>
  <button name="save" text="save" ng-click='save()'>save</button>
  
  <ul>
  	<li ng-repeat='name in names'>{{name.first}}   {{name.last}}</li>
  </ul>
</div>

Upvotes: 1

Related Questions