【问题标题】:Displaying array objects within a array with Angular ng-repeat使用 Angular ng-repeat 在数组中显示数组对象
【发布时间】:2017-09-28 08:42:41
【问题描述】:

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

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

在我有槽的广告系列数组中,槽是一个包含 1 个或多个 base_image 的数组。

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

  • max_slots
  • c_name
  • slots.base_image

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

目标

我正在尝试为每个广告系列制作一个上传图片和预览图片,这样您就只能看到您将其上传到的广告系列的图片预览。

问题

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

见下图:

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();
    })

【问题讨论】:

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


    【解决方案1】:

    您的控制器中只有一个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";
                }
            };
    

    【讨论】:

    • 感谢您这样做是有道理的。我会得到这个实施的测试,并希望能接受你的答案。
    • 只是试图修复一个错误,我得到Uncaught ReferenceError: $index is not defined,一旦它工作不正常接受答案
    • 你是把函数参数命名为index还是$index?在模板中它必须是$index,但在函数中我将它命名为index
    • 是 javascrip 函数它的索引和 html 它的 $index
    • 有什么东西被传递到函数中了吗?如果你传递一些字符串只是为了测试呢?
    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多