但是当我检查单选按钮没有改变ng-model =“title”时我有问题 我经常更改此代码,但我找不到解决方案。有人可以提供帮助,我认为ng-repeat中存在问题吗? 有人可以帮助解决这个问题吗? 我有代码:
<div class="container">
<label data-ng-repeat="option in dbQuestion">
<input type="radio" name="form-field" ng-model="title" value="{{option.title}}" ng-checked="$index == 0" />
{{option.title}}
</label>
<span>{{title}}</span>
</div>
__
var app = angular.module("SampleApp", []);
app.controller("SampleAppCtrl", function($scope) {
$scope.dbQuestion = [{
title: "Question 1",
descripton: "Description 1",
answers: [{
item1: "item1",
value: true
},
{ item2: "item2", value: true },
{ item3: "item3", value: true },
{
item4: "item4",
value: true
}
]
},
{
title: "Question 5",
descripton: "Description 5",
answers: [{
item1: "item1",
value: true
},
{ item2: "item2", value: true },
{ item3: "item3", value: true },
{
item4: "item4",
value: true
}
]
},
];
$scope.title = $scope.dbQuestion[0].title;
});
答案 0 :(得分:2)
新的AngularJS开发人员通常没有意识到ng-repeat
,ng-switch
,ng-view
,ng-include
和ng-if
都会创建新的子范围,因此问题经常出现在涉及这些指令时显示。 (有关问题的快速说明,请参阅this example。)
通过遵循&#34;最佳实践&#34;可以很容易地避免使用原语这个问题。 always have a '.' in your ng-models - 观看3分钟。 Misko用ng-switch
演示了原始绑定问题。
有一个&#39;。&#39;在你的模型中将确保原型继承发挥作用。所以,使用
<label data-ng-repeat="option in dbQuestion">
<input type="radio" name="form-field"
ng-model="title.selected"
value="{{option.title}}"
ng-checked="$index == 0" />
{{option.title}}<br>
</label>
<p>Selected - {{title.selected}}</p>
app.controller("ctrl", function($scope) {
$scope.title = { selected: ''};
$scope.dbQuestion = [{ /*..*/ }];
});
有关详细信息,请参阅AngularJS Wiki - The Nuances of Scope Prototypal Inheritance。
angular.module("app", [])
.controller("ctrl", function($scope) {
$scope.title = { selected: ''};
$scope.dbQuestion = [{
title: "Question 1",
descripton: "Description 1",
answers: [{
item1: "item1",
value: true
},
{ item2: "item2", value: true },
{ item3: "item3", value: true },
{
item4: "item4",
value: true
}
]
},
{
title: "Question 5",
descripton: "Description 5",
answers: [{
item1: "item1",
value: true
},
{ item2: "item2", value: true },
{ item3: "item3", value: true },
{
item4: "item4",
value: true
}
]
},
];
});
&#13;
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<div class="container">
<label data-ng-repeat="option in dbQuestion">
<input type="radio" name="form-field"
ng-model="title.selected"
value="{{option.title}}"
ng-checked="$index == 0" />
{{option.title}}<br>
</label>
<p>Selected - {{title.selected}}</p>
</div>
</body>
&#13;
答案 1 :(得分:0)
You need to use $parent.title
instead of title
, like this :
<input type="radio" name="form-field" ng-model="$parent.title" value="{{option.title}}" ng-checked="$index == 0" />
ng-repeat creates its own scope and in order to assign the value to the parent scope from the child scope we need to use $parent