如何在ng-repeat指令范围之外的条件设置中访问ng-repeat数据?例如,当有人选择ng-repeat中生成的单选按钮时,我想在ng-repeat之外显示div块。
app.js
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.obj = [{
condition: "Question1",
status: "no"
}, {
condition: "Question2",
status: "no"
}];
}
html的
<tr ng-repeat="o in obj">
<td>{{o.condition}}</td>
<td>
Yes
<input type="radio" ng-model="o.status" value="yes" /> No
<input type="radio" ng-model="o.status" value="no" />
</td>
</tr>
<!-- this will show based on an input event-->
<div ng-if="o.status == 'yes'" class="myClass">
I show up
</div>
答案 0 :(得分:1)
我这里有什么在本地工作,但不是当我在js小提琴中尝试时 - 我不知道为什么。
app.js(这就是我习惯定义控制器的方式):
var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.obj = [{
condition: "Question0",
status: "no"
}, {
condition: "Question1",
status: "no"
}];
});
index.html(为h1
中的每个o
单独obj
}:
<body ng-app="myApp">
<div ng-controller="MyCtrl">
<table>
<thead>
<th>Question</th>
<th>Status</th>
</thead>
<tbody>
<tr ng-repeat="o in obj">
<td>{{o.condition}}</td>
<td>
Yes <input type="radio" ng-model="o.status" value="yes" />
No <input type="radio" ng-model="o.status" value="no" />
</td>
</tr>
</tbody>
</table>
<!-- this will display "question 0" and/or "question 1", based on input -->
<div ng-repeat="o in obj">
<h1 ng-if="obj[$index].status === 'yes'" class="myClass">
question {{$index}}
</h1>
</div>
</div>
<script src="app.js"></script>
</body>
答案 1 :(得分:1)
这是不可能的。但你可以尝试这样的事情。
添加功能,检查obj是否有问题&#34; ok&#34;状态
html
<div ng-if="someQuestionIsOk()" class="myClass">
控制器
$scope.someQuestionIsOk = function someQuestionIsOk() {
for(var i = 0; i < $scope.obj.length; i++) {
if($scope.obj[i].status == 'yes')
return true;
}
return false;
}
修改强>
这里是fiddle
修改强>
另一种可能的解决方案是使用ng-change。
HTML
<input type="radio" ng-model="o.status" ng-change="statusChange(o)" value="yes" />
控制器
$scope.answerIsYes = false;
$scope.statusChange = function statusChange(object) {
if(object.status == 'yes')
$scope.answerIsYes = true;
else
$scope.answerIsYes = $scope.someQuestionIsOk();
}