我有一个小的JSON对象,包含国家和城市。
ng-repeat正在呼唤这个国家。所以我现在想要的是,当我点击一个国家/地区项目时,此项目会显示该城市,然后点击其切换回国家/地区。
我有两个功能,我可以将项目从国家切换到城市,但我无法切换回原来的(国家/地区)。我怎么能这样做?
我的HTML:
<body ng-controller="test">
<div ng-repeat="module in values" ng-click="select? setSelected() : setSelected2();select = !select">
{{module.country}}
</div>
和我的.js
文件:
var app = angular.module('AngularApp', []);
app.controller('test', ['$scope', function ($scope) {
$scope.values = [
{
country: 'England',
city: 'London',
},
{
country: 'Spain',
city: 'Madrid',
}];
$scope.select = true;
$scope.setSelected = function() {
$scope.values[this.$index].country = $scope.values[this.$index].city;
}
$scope.setSelected2 = function() {
$scope.values[this.$index].country = $scope.values[this.$index].country;
}
return false;
}]);
这是一个带有我的代码的plunker: https://plnkr.co/edit/MMqDXJFE9dUcWvuGKRDV?p=preview
感谢您的帮助。
答案 0 :(得分:2)
如果它仅用于显示目的,这可以帮助您,而无需将任何Angular函数放在.js
文件中:
<div ng-repeat="module in values" ng-click="select = !select">
{{select ? module.city : module.country}}
</div>
答案 1 :(得分:0)
您应该创建自己的模型来存储显示的值:
$scope.values = [
{
country: 'England',
city: 'London',
showCountry: true
},
{
country: 'Spain',
city: 'Madrid',
showCountry: true
}];
$scope.setSelected = function() {
if ($scope.values[this.$index].showCountry)
{
$scope.values[this.$index].showCountry = false;
} else {
$scope.values[this.$index].showCountry = true;
}
}
<div ng-repeat="module in values" ng-click="setSelected()">
{{module.showCountry ? module.country : module.city}}
</div>