Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs data binding with dynamically created elements

I have this code in my application:

$scope.appendBets = function()
{
    $.each($scope.phaseBets, function(i, bet)
    {
        var betElement = angular.element('<div ng-model="phaseBets[i]">Bet id: {{phaseBets[i].id}}</div>');
        angular.element(document.querySelector('#betsHolder')).append(betElement);
        $compile(betElement)($scope);
    });
}

the $scope.phaseBets is loaded from $http.get.

Now the problem is that the {{phaseBets[i].id}} content not seen on the html page, I am getting this Bet id:.

I have seen this OS but it's not working for me, maybe because of the array. Is there anything wrong with my code?

Note
The thing is that by the I'd I will create an element (different for each id) so ng-repeat not helping that mutch.

like image 568
vlio20 Avatar asked Jul 11 '26 10:07

vlio20


1 Answers

Here's how I'd do it using ng-repeat and ng-include:

$scope.items = [
    {id: 1, title: 'foo', data: {body: 'baz1'}},
    {id: 2, title: 'bar', data: {body: 'baz2'}}
];

<div ng-repeat="item in items">
    <h2>{{item.title}}</h2>
    <div ng-include src="getTemplateById(item.id)"></div>
</div>

Where the templates are defined inline like this:

<script type="text/ng-template" id="template-1.html">
    Content of template-1.html
    <div>{{item.data.body}}</div>
</script>

<script type="text/ng-template" id="template-2.html">
    <p>Content of template-2.html</p>
</script>

and getTemplateById is:

$scope.getTemplateById = function(id) {
    return 'template-' + id + '.html';
};

You can see it in action here.

like image 81
Sergiu Paraschiv Avatar answered Jul 14 '26 02:07

Sergiu Paraschiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!