使用Angular ng-repeat显示数组中的数组对象

时间:2017-09-28 08:42:41

标签: javascript angularjs arrays json angularjs-ng-repeat

我有一个简单的帖子来获取我的json对象。

在我的json中,我有两个或更多的广告系列,广告系列是一个数组。

在广告系列数组中我有插槽,插槽是一个内部有1个或更多base_image的数组。

我在每个广告系列的屏幕上显示。

  • max_slots
  • c_name
  • slots.base_image

这样我就可以展示每个广告系列名称,允许的最大广告位数以及每个广告系列中关联的图片。

AIM

我正在尝试为每个广告系列设置上传图片和预览图片,因此您只能看到上传到该广告系列的图片预览。

问题

目前我上传了一张图片,它会在所有广告系列的预览中显示,而不是单个广告系列。

见下图:

preview in table

HTML

<body ng-app="myApp">
<div ng-controller="Dashboard">
    <!--FIRST ng-repeat-->
    <div ng-repeat="campaign in campaigns" class="campaign-container">
        <div class="container">
            <h1>{{campaign.c_name}} {{$index}}</h1>
            <strong>This Campaign you are allowed {{campaign.max_slots}} Images</strong>
            <table class="table">
                <thead>
                <tr>
                    <th>Select File</th>
                    <th>Preview Image</th>
                    <th>Add to list</th>
                    <th>Images</th>
                    <!--<th>Remove Image</th>-->
                    <th>Save Campaign</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td> <!--UPLOAD IMAGE-->
                        <div class="upload-new">
                            <input id="fileinput" ng-model="file" type="file" ng-model-instant="" name="file"
                                   accept="image/*"
                                   onchange="angular.element(this).scope().uploadImage(this)">
                        </div>
                        <!--END-->
                    </td>
                    <td>  <!--PREVIEW IMAGE-->
                        <div class="preview">
                            <img style="height: 100px; width: 100px" ng-src="{{preview}}" alt="preview image">
                        </div>
                        <!--END--></td>
                    <td>
                        <button ng-click="addImage()">Add image</button>
                    </td>
                    <td>
                        <div ng-repeat="slot in campaign.slots" class="slot">
                            <img ng-click="addImage()" style="height: 100px; width: 100px" ng-src="{{base_image}}"
                                 alt="slot image">

                            <button ng-click="removeImage(slot)">Remove Image</button>
                        </div>
                    </td>
                    <!--<td>Remove button to be here</td>-->
                    <td>
                        <button ng-click="SaveImage()">Save to API</button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
    </div>
    <!--END FIRST ng-repeat-->
</div>
</body>

的JavaScript

    .controller('Dashboard', function ($scope, $http, $timeout) {

        $scope.campaigns = [];
        $scope.preview = '';
        // $scope.slots = [];
        $scope.maxSlots = [5];// this dynamic

        $scope.uploadImage = function () {
            // console.log('we are here');
            input = document.getElementById('fileinput');
            file = input.files[0];
            size = file.size;
            if (size < 650000) {
                var fr = new FileReader;
                fr.onload = function (e) {
                    var img = new Image;

                    img.onload = function () {
                        var width = img.width;
                        var height = img.height;
                        if (width == 1920 && height == 1080) {
                            $scope.preview = e.target.result;
                            $scope.perfect = "you added a image";
                            $scope.$apply();

                        } else {
                            $scope.notPerfect = "incorrect definitions";
                        }
                    };
                    img.src = fr.result;
                };

                fr.readAsDataURL(file);
            } else {
                $scope.notPerfect = "to big";
            }
        };

        $scope.addImage = function (index) {

            if ($scope.campaigns[index].slots.length < $scope.campaigns.maxSlots) {
                $scope.campaigns[index].slots.push({
                    "slot_id": $scope.campaigns[index].slots.length + 1,
                    "base_image": $scope.preview,
                    "path_image": ""
                });

            } else {
                window.alert("you have to delete a slot to generate a new one");
            }
        };

$scope.GetData = function () {
            $http({
                url: "http://www.site.co.uk/ccuploader/campaigns/getCampaign",
                method: "POST",
                date: {},
                headers: {'Content-Type': 'application/json'}
            }).then(function (response) {
                // success
                console.log('you have received the data ');
                // console.log(response);
                $scope.campaigns = response.data;
                console.log("logging campaings", $scope.campaigns);
                //$scope.slots = response.data[0].slots;
                //$scope.maxSlots = response.data[0].maxSlots;

            }, function (response) {
                // failed
                console.log('failed getting campaigns goo back to log in page.');
                // console.log(response);
            });
        };

        $scope.GetData();
    })

1 个答案:

答案 0 :(得分:2)

您的控制器中只有一个preview变量,但每campaign需要一个变量。您可能希望将广告系列的索引传递到uploadImage函数中。

我不确定你做文件输入的方式是否正确(我自己做得不多),但你需要这样的东西:

模板:

<input type="file" onchange="angular.element(this).scope().uploadImage(this, $index)">

<img ng-src="{{campaign.preview}}" alt="preview image">

控制器:

$scope.uploadImage = function (element, index) {
    // Remove this - there are many file inputs with this ID. Use the element or index arguments?
    // input = document.getElementById('fileinput');
    // ...

    if (width == 1920 && height == 1080) {
         $scope.campaigns[index].preview = e.target.result;
    }
}

正如我在上面的评论中所提到的,您也在调用input = document.getElementById('fileinput');来获取文件输入,但ng-repeat将使用该ID创建许多输入。也许你应该使用传递给uploadImage(this, $index)的输入或索引。如果由于某种原因您仍然需要使用getElementById而不是使用您传入的元素,则可以使用索引生成唯一ID:

<input id="fileinput-{{ $index }}" 

编辑:OP使用上面的答案进行了一些修改:

<强> HTML

<input id="fileinput-{{ $index }}" ng-model="file" type="file" ng-model-instant="" name="file" accept="image/*" onchange="angular.element(this).scope().uploadImage(this)">

<强>控制器

    $scope.uploadImage = function (element, index) {
            console.log(element);
            console.log(element.id);
            str = element.id;
            str = str.substr(str.indexOf('-') + 1);
            console.log(str);
            index = str;

            // console.log('we are here');
            input = element;
            file = input.files[0];
            size = file.size;
            if (size < 650000) {
                var fr = new FileReader;
                fr.onload = function (e) {
                    var img = new Image;

                    img.onload = function () {
                        var width = img.width;
                        var height = img.height;
                        if (width == 1920 && height == 1080) {
console.log('we are here');
                            $scope.campaigns[index].preview = e.target.result;
                            // $scope.preview = e.target.result;
                            $scope.perfect = "you added a image";
                            $scope.$apply();

                        } else {
                            $scope.notPerfect = "incorrect definitions";
                        }
                    };
                    img.src = fr.result;
                };

                fr.readAsDataURL(file);
            } else {
                $scope.notPerfect = "to big";
            }
        };
相关问题