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/
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/
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);
}]);
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.
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>