2种类型的数据JSON&用AngularJS解析

时间:2016-08-11 16:35:30

标签: javascript angularjs json

我有正确解析JSON的问题。我有两种类型的数据,我希望根据它们的类型显示这些数据。 Actualy,我可以显示1种类型的数据(在另一个例子中)。谢谢你的帮助。

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>

控制器

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

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

            $scope.values = data;

        });

}]);

1 个答案:

答案 0 :(得分:0)

我为你的案子做了一个小提琴:http://jsfiddle.net/k64bdxrb/

看看

<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>