2

Is it possible to parse JSON inside an ng-repeat? I tried both JSON.parse and angular.fromJson.

    <div ng-repeat='x in JSON.parse(element.info)'>
        {{x.key}}
    </div>

It can be checked here: http://jsfiddle.net/y4qje54o/1/

EIZ
  • 105
  • 1
  • 7
  • Just parse it on the controller, or from the service that returns this. otherwise you would need to add JSON.parse on the $scope. binding expressions are evaluated against the scope. `$scope.parse = JSON.parse` on the controller and then use `parse(element.info)` on the view. I wouldn't do that though. Check out **[this answer](http://stackoverflow.com/questions/25299436/unable-to-call-object-keys-in-angularjs)** – PSL Dec 12 '14 at 22:47

3 Answers3

1

Why you don't want to do like this ?

var ngApp = angular.module('ngApp',[]);
var ngCtrl = ngApp.controller('ngCtrl',['$scope', function($scope){

    $scope.elements = [];
    $scope.element = {};
    $scope.element.title = 'first element';
    //this comes from DB like this(as string)
    $scope.element.info = JSON.parse('[{"key":"value1"},{"key":"value2"}]');

    $scope.elements.push($scope.element);
}]);
dotnetstep
  • 17,065
  • 5
  • 54
  • 72
  • 1
    I get an array of elements from a webAPI and I don't want to loop the array to apply JSON.parse in the controller. I was hoping I can do it when I get to use the elements in the template. – EIZ Dec 12 '14 at 23:00
  • 1
    In AngularJS you have to provide Model to View. Responsibility of View is to render based on Model data. – dotnetstep Dec 12 '14 at 23:04
  • 1
    Valid point! I was looking at the option with the ng-repeat thinking that looping through the array in the controller/service would be a performance overhead that I could avoid. – EIZ Dec 12 '14 at 23:06
1

AngularJS handles all ng-repeat with a $watch module nested and hard coded inside the core. If you try to write an uncorrect ng-repeat it will cause a log error spam, this is due to the "reloading" of the ng-repeat loop.

If you put a JSON parse inside a loop it will cause a huge performance breakdown. From controller you will do it once.

Notice that if the view were generating the data once, then performance will be equal. But you will lose MVC pattern. Take care about it.

greenfox
  • 208
  • 1
  • 9
0

Check it here: https://jsfiddle.net/y4qje54o/4/

Same results, but I did it using split, slice & indexOf instead of JSON.parse.

Code:

<div ng-repeat="x in temp=angular.equals(temp,element.info.slice(1, -1).split(','))?temp:element.info.slice(1,-1).split(',')">
    {{x.slice(x.indexOf(':')+2, -2)}}
</div>
Leopoldo Sanczyk
  • 1,529
  • 1
  • 26
  • 28