ng-repeat中的动态ng-模型未定义

Dynamical ng-model in ng-repeat is undefined

本文关键字:模型 未定义 ng- 动态 ng-repeat      更新时间:2023-09-26

我需要在ng-repeat中动态生成模型的帮助。我有一个HTML与ng重复表行。每一行都有一个更新按钮来更新图片名称和价格的选项。

HTML

<tr role="row" class="odd" ng-repeat="i in slideShowImages track by $index">
    <td>
        <img ng-src="{{i.thumb_path}}" width="100px" height="auto" >
    </td>
    <td>
        <div class="form-group">
            <input type="text" name="imageName" ng-model="i.imageName[$index]"
                   class="form-control" id="imageName" required>
        </div>
    </td>
    <td>{{i.date_taken | myDate}}</td>
    <td>
        <div class="form-group">
            <input type="text" name="imagePrice" ng-model="i.imagePrice[$index]"
                   class="form-control" id="imagePrice" required>
        </div>
    </td>
    <td>
        {{i.position}}
    </td>
    <td>
        <a ng-click="updateImage(i.id_thumb, $index)">
            <button class="btn btn-block btn-success">Update</button>
        </a>
    </td>
    <td>
        <a ng-click="deleteImage(i.id_thumb, $index)">
            <button class="btn btn-block btn-danger">Delete</button>
        </a>
    </td>
</tr>

这是我的控制器函数它试图获取值

$scope.updateImage = function(id, $index){
    $scope.models = {};
    console.log(id);
    console.log($index);
    console.log($scope.i.imageName[$index]);
    console.log($scope.i.imagePrice[$index]);
};
// result of console logs
4
0
angular.js:13550 TypeError: Cannot read property 'imageName' of undefined
    at Scope.$scope.updateImage (locationsCtrl.js:243)
    at fn (eval at compile (angular.js:14432), <anonymous>:4:486)
    at expensiveCheckFn (angular.js:15485)
    at callback (angular.js:25018)
    at Scope.$eval (angular.js:17229)
    at Scope.$apply (angular.js:17329)
    at HTMLAnchorElement.<anonymous> (angular.js:25023)
    at HTMLAnchorElement.dispatch (jQuery-2.1.4.min.js:3)
    at HTMLAnchorElement.r.handle (jQuery-2.1.4.min.js:3)

猜我做错了,基于错误的imageName和imagePrice不能被定义。我希望你们能帮我。如果你需要任何额外的信息,请让我知道,我将提供。提前谢谢大家

你有ng-repeati in slideShowImages,这表明,在每次迭代中,i将仅在UI上(不在控制器范围内)收集当前元素。因此在控制器内部无法得到$scope.i值。您必须将updateImage的值作为ng-click="updateImage(i)"的参数传递。然后你可以在UI上使用i对象。

<td>
    <a ng-click="updateImage(i)">
        <button class="btn btn-block btn-success">Update</button>
    </a>
</td>
<td>
    <a ng-click="deleteImage(i, $index)">
        <button class="btn btn-block btn-danger">Delete</button>
    </a>
</td>
控制器

$scope.updateImage = function(i){
    console.log(i.imageName);
    console.log(i.imagePrice);
};

不能在控制器中获取ng-repeati对象。我们还可以使用json.

中的任何其他键进行过滤。

的例子:

$scope.currentImageName = $filter('filter')(slideShowImages,{ id: $index});

这里假设slideShowImages有一个字段id值- $index

同时,在控制器定义中添加依赖注入$filter