此处为 Angular 1 应用。
我有这个名为 data.json 的 json 文件:
[
{
"rejectionType": "REJECTION_1",
"user": "ALL",
"selected": false
},
{
"rejectionType": "REJECTION_2",
"user": "MALE",
"selected": false
},
{
"rejectionType": "REJECTION_3",
"user": "FEMALE",
"selected": false
}
]
在 Controller 中,我执行以下操作:
$http.get('data.json').then(function(response) {
var rejectionData = response.data;
myctrl.currentRejections = _.filter(rejectionData, function(item, index) {
return _.contains(["ALL", "MALE"], item.user);
})
console.log("myCtrl.currentRejections:",myCtrl.currentRejections);
$("#modRejectionReason").modal("show");
});
View 中的模式看起来像这样:
<div id="modRejectionReason">
<div class="modal-body">
<p>
<div ng-repeat="allrejections in myctrl.currentRejections">
<p>
<input type="radio" name="selected" ng-model="allrejections.selected" />
{{allrejections.rejectionType}}
</p>
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" ng-click="myctrl.func()">OK</button>
</div>
</div>
</div>
</div>
然后在 Controller 中我有这个:
var declineInvite = function () {
console.log("myctrl.currentRejections:",myctrl.currentRejections);
}
在日志中我看到当模态出现时,变量 myCtrl.currentRejections
被打印。它是一个包含所有过滤元素的数组。
对于每个元素,我都看到字段 selected
是 false。
当我选中一个单选按钮,然后单击 OK-button
时,函数 func
被触发。
即使在这里,相同的数据也会打印在控制台中。但是,对于在 json 中单击的那些单选按钮,字段 selected
的值是未定义的。
我在这里缺少什么?
最佳答案
您需要给单选按钮一个值,以便在它们被选中时设置。
<input type="radio" name="selected" ng-model="allrejections.selected" ng-value="true"/>
在当前代码中这样做的问题是 selected:true
永远不会被取消设置,所以我建议在 Controller 上添加一个名为 selectedRejection
的新值,并且使用它作为模型并将值设置为实际的拒绝对象。这样做意味着您也可以摆脱 JSON 数据上的 selected 属性!
var myApp = angular.module('myApp', []).controller("MyCtrl", MyCtrl);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl() {
var MyCtrl = this;
MyCtrl.currentRejections = [{
"rejectionType": "REJECTION_1",
"user": "ALL",
"selected": false
},
{
"rejectionType": "REJECTION_2",
"user": "MALE",
"selected": false
}
]
MyCtrl.selectedRejection = null;
MyCtrl.submit = function() {
console.log(MyCtrl.selectedRejection)
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl as MyCtrl">
<div ng-repeat="allrejections in MyCtrl.currentRejections">
<p>
<input type="radio" name="selected" ng-model="MyCtrl.selectedRejection" ng-value="allrejections" /> {{allrejections.rejectionType}}
</p>
</div>
<button type="button" ng-click="MyCtrl.submit()">OK</button>
</div>
</body>
关于javascript - Json模型在 Angular 上没有绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52591342/