DaveLV2
DaveLV2

Reputation: 358

Trying to output html with angular js

Im trying to output html with angular js. I know the html is going to be ok. This is what im trying now:

<div class="items-list" id="items-container">
        <div ng-repeat="data in ItemsData track by $index" ng-bind-html='ItemsData'>
            <-data->
        </div>
    </div>

And this is what i pretty much am doing with the data

$.ajax({
                        method: "POST",
                        url: "{{URL::route('items')}}",
                        data: filteringData,
                        dataType: 'json'
                    }
            ).done(function (response) {
                        $scope.ItemsData = $sce.trustAsHtml(response['items']);
                        $scope.ItemsPage += 1;
                        $scope.ItemsLastPage = response['lastPage'];
                        $scope.ItemsLoaderBusy = false;
                    });

But this is not working. Im trying to do this for a long time.

Pretty much what I want is that I get a response from the server. It has 'items'. Its an array of elements that are html. How could I output them with a repeat?

And I really dont know what im doing. Thanks for help.

Upvotes: 1

Views: 241

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

You have to use the data variable which you have defined in ng-repeat for binding inside ng-bind-html. So change ItemsData to data.

<div ng-repeat="data in ItemsData track by $index" ng-bind-html='data'>
   <-data->
</div>

Also as you commented to the question you are getting error when executing $sce.trustAsHtml method, it is because you are passing an array response['items']when it expects a string.

Assuming response['items'] as an array of string you can try this.

$.ajax({
    method: "POST",
    url: "{{URL::route('items')}}",
    data: filteringData,
    dataType: 'json'
}).done(function(response) {
    $scope.ItemsData = [];
    angular.forEach(response.items, function(item) {
       $scope.ItemsData.push($sce.trustAsHtml(item));
    });
    $scope.ItemsPage += 1;
    $scope.ItemsLastPage = response['lastPage'];
    $scope.ItemsLoaderBusy = false;
});

Also as pointed by @pankajparkar you should try to use $http instead of jQuery ajax because it will run the digest cycle.

Upvotes: 1

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You should never have been use $.ajax, that should be replaced the ajax call using $http service. Using $.ajax will not run digest cycle on its completion where $http does run digest cycle after callback gets called

Additionally your ng-bind would be ng-bind-html="trustedAsHtml(data)"

then your controller will have one method trustedAsHtml that will html as trusted using $sce service

$scope.trustedAsHtml = function(data){ return $sce.trustedAsHtml(data); }

Upvotes: 2

Related Questions