我有一个简单的问题,我想通过以下方式实现以下目标:
我希望{{gender}}
的默认值为undefined或其他。
用户点击男性或女性后,我想隐藏父ul
并显示selectedGender <li>
并在完成后更新{{gender}}
字段。但是,当用户点击selectedGender <li>
时,我想要撤销所有内容并将{{gender}}
设置为未定义(默认值)。
<ul class="col">
<li class="two" ng-click="selectedGender = true">Male</li>
<li class="two" ng-click="selectedGender = true">Female</li>
</ul>
<li ng-show="selectedGender" ng-click="">{{gender}}</li>
谢谢!
答案 0 :(得分:1)
您可以执行以下操作:
<ul class="col" ng-show="selectedGender == false">
<li class="two" ng-click="selectedGender = 'male'">Male</li>
<li class="two" ng-click="selectedGender = 'female'">Female</li>
</ul>
<li ng-show="!!selectedGender" ng-click="selectedGender = false">{{selectedGender}}</li>
当然,将所有内容包装在更好的函数中会更好。
<ul class="col" ng-show="currentGender == false">
<li class="two" ng-click="selectGender('male')">Male</li>
<li class="two" ng-click="selectGender('female')">Female</li>
</ul>
<li ng-show="!!currentGender" ng-click="selectGender(false)">{{currentGender}}</li>
然后,在$ scope中有一个函数selectGender:
$scope.selectGender = function(gender){
$scope.currentGender = gender;
}
在javascript中!!
用作boolean
的强制转换。首先!
将对象转换为boolean
,然后第二个验证条件。
Jsfiddle here
答案 1 :(得分:0)
ng-click属性可以指定在控制器范围内调用的函数,然后可以修改所需的值。
$ scope.selectGender = function(){$ scope.selectedGender = true; } $ scope.unselectGender = function(){$ scope.selectedGender = null; }
&lt; .. ng-click =“selectGender()”.. /&gt;
答案 2 :(得分:0)
我想出的答案并不是很干,但它确实有效。所以你可能想根据自己的需要修改它。我基本上把男性和女性都带到了复选框中,这样他们就会返回真值或假值。我使用该模型来比较它们是否是某种性别并将其用作显示的内容。对于单击性别本身,我将所有值删除为默认值null。希望有所帮助。
这是一支工作笔 http://codepen.io/ddavisgraphics/pen/raWZGd
以下是我用来提出解决方案https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D
的API文档HTML
<body ng-app="app">
<ul ng-controller="GenderCtrl">
<li> Whats your Gender
<ul class="col">
<li class="two">
<input type="checkbox" ng-model="maleValue" ng-click="userGender()" value="male"/>
Male
</li>
<li class="two">
<input type="checkbox" ng-model="femaleValue" ng-click="userGender()" value="female"/>
Female
</li>
</ul> </li>
<li ng-click="removeGender()" ng-Show="selectedGender"> Your current {{gender}} </li>
</ul>
</body>
JS
var app = angular.module('app', []);
app.controller("GenderCtrl", function ($scope) {
$scope.gender = ""; // Leave it undefined but set the variable
$scope.maleValue = null;
$scope.femaleValue = null;
$scope.selectedGender = false;
$scope.userGender = function(){
$scope.selectedGender = true;
if($scope.maleValue === true) {
$scope.gender = "Male";
console.log('testing male');
} else if ($scope.femaleValue === true) {
$scope.gender = "Female";
console.log('testing female');
} else {
$scope.gender = null;
$scope.selectedGender = false;
}
}
$scope.removeGender = function(){
$scope.gender = null;
$scope.maleValue = null;
$scope.femaleValue = null;
}
});