Javascript 如何将索引值从ng repeat在Angular中传递给控制器
我正在动态创建div,同时单击包含一些单选输入的按钮。在控制器中,我有一个用于divs填充的数组,其初始长度为1Javascript 如何将索引值从ng repeat在Angular中传递给控制器,javascript,angularjs,Javascript,Angularjs,我正在动态创建div,同时单击包含一些单选输入的按钮。在控制器中,我有一个用于divs填充的数组,其初始长度为1 'use strict'; angular.module('load').controller( 'commodityController', function($scope, $http, $state, $stateParams) { $scope.parentload = $scope.$parent.load;
'use strict';
angular.module('load').controller(
'commodityController',
function($scope, $http, $state, $stateParams) {
$scope.parentload = $scope.$parent.load;
$scope.addMoreCommodities = function() {
$scope.parentload.loadCommodities.push({
'isHazmat' : false,
'dimension' : 'IN'
});
}
$scope.parentload.loadCommodities = []; // emtry array
$scope.addMoreCommodities(); // Here initialize the array
$scope.changeHazmat = function(booleans, val) {
console.log("booleans " + booleans);
console.log("isactive " + val);
$scope.parentload.loadCommodities[val].isHazmat = booleans;
};
});
使用以下html,在加载页面div时
<div class="form-right-card disabledInput" ng-init="showname==true" id="commodityContent">
<form name="commodityAttForm">
<div ng-repeat="loadCommodities in load.loadCommodities">
<div class="form-group33"> {{$index}} // here value prints correctly
<label class="form-label">Hazmat</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('true',$index)" id="yes" name="hazmat" />
<label class="plsLabel" for="yes">Yes</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('false',$index)" id="no" name="hazmat" />
<label class="plsLabel" for="no">No</label>
</div>
</div>
</form>
</div>
<button class="form-btn-link" ng-click="addMoreCommodities()">+ Add Commodity</button>
日志始终将索引打印为0
有人能帮我一下吗,我做错了什么?您正确地传递了
$index
控制器,代码应该可以工作
但是,我建议使用with指令
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />
危险品
对
不
{{parentload.loadproductions}
我想知道问题是否在于您将相同的“id”(“是”和“否”)分配给多个div(即循环内部)。这可能是$index不适合您的原因。如果您暂时删除id并重试,我认为问题会消失。您可以查看此演示吗?它正在按你的预期工作,对吗?这不是重点,但是当您将字符串“true”、“false”传递到changeHazmat而不是布尔值(不带引号)时,您可能会遇到问题。谢谢您的回答。。。我有下面这张照片。能够按预期发送索引。但第二行也只选择了一个单选值。我想在每行中选择一个。
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />