编辑:当我在表单中更改ng-model =“$ parent.selectedAnswer”时,它可以正常工作。如果有人可以解释,我会将其标记为答案。
我正在尝试在“下一步”按钮单击时将选定的单选按钮值收集到角度函数,但它始终未定义。我无法弄清楚出了什么问题。单选按钮和值在html中正确填充。只有在单击下一步并尝试传入选定值时才会失败。
我的逻辑很简单:每个单选按钮的值是[branchid,leafid,answerid]的数组。当单击next时,我尝试将该值绑定到“selectedAnswer”模型并将其传递给angularjs端的next()函数。
以下是相关代码:
app.controller('GameNode', function ($scope, $http) {
function load(selectedAnswer) {
var leafId = 0, branchId = 0, answerId = 0;
alert(selectedAnswer); //this is always undefined
if (selectedAnswer !== undefined && selectedAnswer != null) {
branchId = selectedAnswer[0];
leafId = selectedAnswer[1];
answerId = selectedAnswer[2];
}
$http.get("/AccountRequest/GetNode?branchId=" + branchId +
"&leafId=" + leafId +
"&answerId=" + answerId)
.success(function(data) {
$scope.node = data;
});
}
$scope.next = load;
load();
});
------------------------------------- html side -------- ---------------------------
<div class="container-fluid" ng-app="AccountRequest" ng-controller="GameNode">
<div class="row-fluid">
<div class="span2"></div>
<div class="span10">
<form>
<span>{{node.Question.Text}}</span>
<div class="radio" ng-repeat="answer in node.Answers">
<input type="radio" id="answerGroup" name="answerGroup" ng-model="selectedAnswer"
value="[{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}]"/> {{answer.Text}}
</div>
<div>
<input type="button" ng-click="next(selectedAnswer)" value="Next" id="Next"/>
</div>
</form>
</div>
</div>
</div>
答案 0 :(得分:1)
我认为这是因为ng-repeat为每个项目创建了一个新的子范围,并且由于selectedAnswer
未在重复项selectedAnswer
之外进行初始化,因此父项中undefined
始终为 <form ng-init="outside={}">
<span>{{node.Question.Text}}</span>
<div class="radio" ng-repeat="answer in node.Answers">
<input type="radio" id="answerGroup" name="answerGroup" ng-model="outside.selectedAnswer"
value="[{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}]"/> {{answer.Text}}
</div>
<div>
<input type="button" ng-click="next(outside.selectedAnswer)" value="Next" id="Next"/>
</div>
</form>
范围。您可以通过执行以下操作来解决此问题:
{{1}}
答案 1 :(得分:0)
如果在控制器中定义$ scope.selectedAnswer,是否可以解决问题?
app.controller('GameNode', function ($scope, $http) {
$scope.selectedAnswer = null;
function load(selectedAnswer) {
var leafId = 0, branchId = 0, answerId = 0;
alert(selectedAnswer); //this is always undefined
if (selectedAnswer !== undefined && selectedAnswer != null) {
branchId = selectedAnswer[0];
leafId = selectedAnswer[1];
answerId = selectedAnswer[2];
}
$http.get("/AccountRequest/GetNode?branchId=" + branchId +
"&leafId=" + leafId +
"&answerId=" + answerId)
.success(function(data) {
$scope.node = data;
});
}
$scope.next = load;
load();
});
如果没有,请为我们创建一个jsFiddle来使用。