Neeraj Neeraj - 2 years ago 202
HTML Question

Dynamically add elements each time with new scope in angular js

Each time I append an li to my ul i want new id like new_id_(index_number) i.e( id_1, id_2 so on. ). I am using a template to which contains li to be appended , the reason i am using a template because it contains a lot of data like 3-4 forms which has too-many fields. I am using the following code :

My Code Snippet:

<div ng-controller="ContractsController">
<ul id="contracts">
<li id="new_{{indx}}"></li>
<button class="add_new" add-contracts>Add New Item</button>
<script type="text/javascript">

var app = angular.module('AjApp', []);

app.controller('ContractsController', function ( $scope ) {
$scope.indx = 1;

app.directive('addContracts', function ( $templateRequest, $templateCache, $compile ) {
return {
restrict: 'A',
scope: true,
link: function(scope, ele, attr) {

ele.on("click", function(e) {
var $contracts = jQuery("ul#contracts");

$templateRequest("add_contracts.html" ).then(function(html){
var template = angular.element(html);



The code is appending the li to the ul but each time I click on Add New Item button all of the li's updated to same id .

What is the problem ? Am I missing something ? Please suggest me a way to solve the problem. Any help will really appreciate. Thanks in advance.

Answer Source

You could create a new child scope for each contract, and each child scope contains its own id.

Also, The logic handled by the add-contracts directive could probably be handled by the controller. That way you don't have to select the div using jQuery("ul#contracts"). In my example I changed it to use a css class, and the selector becomes $element.find('.contracts').

Here's an example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download