Kevin Py Kevin Py - 3 months ago 11
AngularJS Question

2 type of datas JSON & parse with AngularJS

I have a problem for parse my JSON correctly. I have 2 types of datas, and I wish display this data depending their type. Actualy, I can display 1 type of data (on an other example). Thank you for your help.

JSON

[
{
"id": 0,
"type": "two",
"color1": {
"hex": "#fc2a19",
"rgb": "252, 42, 25"
},
"color2": {
"hex": "#fc5fa6",
"rgb": "252, 95, 166"
}
},
{
"id": 1,
"type": "one",
"color1": {
"hex": "#58eaa1",
"rgb": "88, 234, 161"
}
},
{
"id": 2,
"type": "one",
"hex": "#ef456a",
"rgb": "239, 69, 106"
},
// Others


HTML

<ng-if="value.type == 'one">
<li class="gradient" ng-repeat="value in values | filter: filterColor">
<div class="" style="background: {{ value.hex }}"></div>
<span>
<p>{{ value.hex }}</p>
<p>{{ value.rgb }}</p>
</span>
</li>
</ng-if>
<ng-if="value.type == 'two">
<li class="gradient bicolor" ng-repeat="value in values | filter: filterColor">
<div class="" style="background: linear-gradient(to top, {{ value.color1.hex }}, {{ value.color2.hex }})"></div>
<span>
<p>{{ value.color1.hex }}</p>
<p>{{ value.color1.rgb }}</p>
</span>
<span>
<p>{{ value.color2.hex }}</p>
<p>{{ value.color2.rgb }}</p>
</span>
</li>
</ng-if>


Controller

angular.module('myApp').controller('gradientsCtrl', ['$scope', '$http', function($scope, $http) {

$http.get("./values-alt.json")
.success(function(data, status) {

$scope.values = data;

});

}]);

Answer

I've made a fiddle for your case: http://jsfiddle.net/k64bdxrb/

Take a look

<div ng-repeat="value in values">
    <div ng-if="value.type == 'one'" style="border: 1px solid red;">
        <div ng-if="!!value.color1">
            <p>{{ value.color1.hex }}</p>
            <p>{{ value.color1.rgb }}</p>
        </div>
        <div ng-if="!value.color1">
            <p>{{ value.hex }}</p>
            <p>{{ value.rgb }}</p>
        </div>
    </div>
    <div ng-if="value.type == 'two'" style="border: 1px solid green;">
        <span>
            <p>{{ value.color1.hex }}</p>
            <p>{{ value.color1.rgb }}</p>
        </span>
        <span>
            <p>{{ value.color2.hex }}</p>
            <p>{{ value.color2.rgb }}</p>
        </span>
    </div>
</div>