简体   繁体   中英

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.

I think you got it from wrong side, in angularjs controllers/data drives the view, here you are creating elements (and even worse adding them to page) in loop (expensive DOM operations) I'd replace your code with following

<div id="betsHolder">
  <div ng-repeat="bet in phaseBets track by bet.id">Bet id: {{bet.id}}</div>
</div>

as soon as you assign your array/object to $scope.phaseBets the DOM will be created

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.

but using ng-repeat is better option,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM