我在$http.get
请求中获得了一系列对象。我正在做以下操作:
$http.get("/showdata").then(function (response) {
var thedata = response.data.category;
console.log(thedata);
$scope.alldata = response.data;
if (thedata === "school") {
$scope.category = "SchoolBC";
} else {
$scope.category = "Not School";
}
});
如何检查响应中的某些内容并相应地设置$scope
?
我得到的回报是:
[
{
id: "123456",
category: "school",
title: "first test"
},
{
id: "789012",
category: "home",
title: "second test"
}
]
在前端我有:
<ul ng-repeat = "mydata in alldata">
<li>{{mydata.title}}<p>{{category}}</p></li>
</ul>
根据评论和编辑您的问题更新了答案。循环通过数组中的对象,并根据条件覆盖对象属性:
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
var thedata = [
{
id: "123456",
category: "school",
title: "first test"
},
{
id: "789012",
category: "home",
title: "second test"
},
{
id: "789012",
category: ['home', 'school', 'primary', 'pre-primary', 'test', 'test1', 'test2' ],
title: "third test"
}
];
function overrideObjectValue(data) {
angular.forEach(data , function(value, key){
if(typeof value.category === 'object') {
if ($.inArray('school', value.category)) {
data[key].category = "SchoolBC";
} else {
data[key].category = "Not School";
}
} else {
if (value.category === "school") {
data[key].category = "SchoolBC";
} else {
data[key].category = "Not School";
}
}
});
return data;
}
$scope.alldata = overrideObjectValue(thedata);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul ng-repeat = "mydata in alldata">
<li>{{mydata.title}}<p>{{mydata.category}}</p></li>
</ul>
</div>