angularjsangularjs-templates

angularjs $compile html template in forEach not update variables


I want to dynamically generate html. I have generateHtml function contains loop for items, currently it is not displaying proper variables added in template. It is always display the last items data on all the iteration on compiled html. Following is the controller & template code

This is my controller code

angular.module('app').controller('PageController', ['$scope', '$sce', '$compile','$templateRequest',
    function ($scope, $sce, $compile,$templateRequest) {
        $scope.itemsHtml = '';
        // Array contains dynamic data
        vm.items = [{
            id: 1,
            name: 'abc',
        }, {
            id: 2,
            name: 'pqr',
        }, {
            id: 3,
            name: 'stu',
        }, {
            id: 4,
            name: 'xyz',
        }];
        vm.currentItem = [];
        
        let templateUrl = $sce.getTrustedResourceUrl('/views/item.html');

        $templateRequest(templateUrl).then(function(template) {
            vm.itemTemplate = template;
        }, function() {
        });

        vm.generateHtml = function() {
            items.forEach(function (item, key) {
                vm.currentItem = item;

                let compiledTemplate = $compile(vm.itemTemplate)($scope).html();

                /* Append compiled dynamic html */
                $scope.itemsHtml += compiledTemplate;
            });
        }

        function init() {
            vm.generateHtml();
        }
        
        init();
    }
]);

This is template view

<script type="text/ng-template" id="item.html">
    <div className="item-wrapper">
        <div className="item-inner">
            {{ pageCtrl.currentItem.name }}
        </div>
        <div className="action-inner">
            <div className="btn-action"
                 role="button"
                 ng-click="pageCtrl.edit(
                                pageCtrl.currentItem.id
                            )">
                <i className="fa fa-plus"></i>
            </div>
        </div>
    </div>
</script>

Solution

  • I got the solution for this issue.

    Actually when we use compile after that we have to interpolate the compiled template

    compiledTemplate = $interpolate(compiledTemplate)($scope);

    let compiledTemplate = $compile(vm.itemTemplate)($scope).html();
    
    /* Here interpolated compiled template */
    compiledTemplate = $interpolate(compiledTemplate)($scope);
    
    /* Append compiled dynamic html */
    $scope.itemsHtml += compiledTemplate;