我是新手,我从服务器收到一条JSON消息,并且收到下面提到的消息(我从服务器得到JSON数组),我试图最好地解析我的级别,但没有结果,我如何在上面解析在给定的JSON消息下方带有 fruit 对象下面的对象可以帮助我吗?
[
{
FruitId: 1,
"Name": "Apple",
},
{
FruitId: 2,
"Name": "Orange",
},
{
FruitId: 3,
"Name": "Bananna",
}
]
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
var fruit={
FruitId:0,
Name: '',
Selected:false
}
$scope.Fruits = [];
$scope.GetValue = function () {
var message = "";
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].Selected) {
var fruitId = $scope.Fruits[i].FruitId;
var fruitName = $scope.Fruits[i].Name;
message += "Value: " + fruitId + " Text: " + fruitName + "\n";
}
}
$window.alert(message);
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<div ng-repeat="fruit in Fruits">
<label for="chkCustomer_{{fruit.FruitId}}">
<input id="chkCustomer_{{fruit.FruitId}}" type="checkbox" ng-model="fruit.Selected" />
{{fruit.Name}}
</label>
</div>
<br />
<br />
<input type="button" value="Get" ng-click="GetValue()" />
</div>
答案 0 :(得分:0)
在问题中,您想解析3个项目的数组,对吧?
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [];
var fruit1={FruitId:1, Name: 'Apple',Selected:false };
var fruit2={FruitId:2, Name: 'Orange',Selected:true };
var fruit3={FruitId:3, Name: 'Banana',Selected:false };
$scope.Fruits.push(fruit1);
$scope.Fruits.push(fruit2);
$scope.Fruits.push(fruit3);
$scope.GetValue = function () {
var message = "";
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].Selected) {
var fruitId = $scope.Fruits[i].FruitId;
var fruitName = $scope.Fruits[i].Name;
message += "Value: " + fruitId + " Text: " + fruitName + "\n";
}
}
console.log(message);
alert(message);
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<div ng-repeat="fruit in Fruits">
<label for="chkCustomer_{{fruit.FruitId}}">
<input id="chkCustomer_{{fruit.FruitId}}" type="checkbox" ng-model="fruit.Selected" />
{{fruit.Name}}
</label>
</div>
<br />
<br />
<input type="button" value="Get" ng-click="GetValue()" />
</div>