Search code examples
javascriptjqueryhtmlangularjsangularjs-scope

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>
 </ul>
<button class="add_new" add-contracts>Add New Item</button>
</div>
<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) {
                e.preventDefault();
                var $contracts = jQuery("ul#contracts");
                ++scope.indx;

               $templateRequest("add_contracts.html" ).then(function(html){
                  var template = angular.element(html);
                  $contracts.append(template);
                  $compile(template)(scope);
               });


            });
        },
    };
});


</script>

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.


Solution

  • 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:

    http://jsfiddle.net/rs1whmo7/