如何在ng-repeat中传递选定的$ index?

时间:2016-04-17 08:17:41

标签: javascript html angularjs pug

我想上传图片并显示在页面中。我有5个图像,所以有5个阵列,我用ng-repeat来显示它。

以下是我的玉石形式:

                form.form-horizontal       
                    .form-group(ng-repeat="runningText in runningTexts")
                        .col-md-3
                            label.control-label Image {{$index+1}}
                            .image-upload-area.label-centerleft
                                p(onclick="$('#imageFile').click()") Click me to change
                                img.loading(ng-show="isUploading" src="/img/loading.gif")    
                                img.img-responsive.clickable(ng-src="{{runningText.image != '' ? '/img/' + runningText.image : '/img/logo_d.png'}}")                                    

                form#imageUpload(enctype="multipart/form-data" action="/api/admin/display/image" ng-upload="uploadDone(content)" method="post")
                    input#imageFile(type="file" name="image" onChange="$('#imageSubmit').click();return false;" style="display:none")
                    input#imageSubmit(type="submit" ng-click="isUploading = true"  style="display:none") 

以下是我的js文件中的控制器:

    loadData = function(){  //page load function
    $http.get(apiPath)
        .success(function(data){  
            if (data != null){       
                $scope.runningTexts = data.displaySetting.runningText;
            }
        })  
    }  

    $scope.uploadDone = function(data) {  // upload finished function
    $scope.runningTexts[0].image = data.path;  // Problem here!!
    $scope.isUploading = false;
};

如何传递我在html中选择的索引并将其放回$ scope.runningTexts [0] .image中。现在我使用0,所以我上传的每个图像都只显示在数组0中。如果我上传到阵列1或2等,我该怎么办?

1 个答案:

答案 0 :(得分:0)

你需要在Image的click事件中调用一个函数,并将$ index作为参数传递给它。

 <div ng-app="myApp" ng-controller="MainCtrl">
<ul>
    <li ng-repeat="page in pages">
        <a ng-class="{ testClass: $index == pageNumber }" ng-click="setPageNumber($index)">{{ page }}</a>
    </li>
</ul>

  var app = angular.module('myApp', []);

  app.controller('MainCtrl', function($scope) {
  $scope.pages = [
    'Page One',
    'Page Two',
    'Page Three'
];

$scope.pageNumber = 0;
$scope.setPageNumber = function(index) {
    $scope.pageNumber = index;
    console.log(index)
}

});

你可以查看这个小提琴。

http://jsfiddle.net/razh/NFNvc/