我很有角度:)。我想添加一个简单的事件,一个具有特定值的表单元素,由ng-repeat构建。这就是HTML的外观:
<div class="labels">
<div class="checkbox-element" ng-repeat="suggestName in $ctrl.suggests" ng-click="$ctrl.toggleSelection(suggestName, 'suggestsSelection', this)">
<label>
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
value="{{suggestName}}"
><span></span>{{suggestName}}
</label>
</div>
<div class="optionary hidden">
<br>
<div class="question__text">Any other?</div>
<label><input type="text"
ng-model="$ctrl.survey.suggest_other"
name="suggests_other1"></label><br>
</div>
</div>
控制器代码:
vm.survey = {};
vm.suggests = ['quality', 'price', 'habbit', 'other'];
// selected
vm.survey.suggestsSelection = [];
// toggle selection for a given names
vm.toggleSelection = function toggleSelection(value, array, scope) {
var idx = vm.survey[array].indexOf(value);
// is currently selected
if (idx > -1) {
vm.survey[array].splice(idx, 1);
}
// is newly selected
else {
vm.survey[array].push(value);
}
};
我需要的是创建一个事件,在点击最后创建的复选框(在这种情况下为“其他”)后,将“隐藏”类与div“optionary”类切换。单击其他复选框不应影响“选项”div。
我尝试了一些配置,如:
if(scope.$last){
$(scope).closest('.optionary').toggleClass('hidden');
}
或类似的。我不知道应该如何处理这个话题。
答案 0 :(得分:1)
正如您所看到的,ng-repeat具有特殊属性:https://docs.angularjs.org/api/ng/directive/ngRepeat
您感兴趣的是$last
。您可以将ng-change
添加到复选框,使用参数$last
调用函数,该函数将设置范围变量。 hidden
类可以依赖它。
这样的事情:
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
ng-change="showHidden($last)"
value="{{suggestName}}">
在你的控制器中:
$scope.hidden = true;
$scope.showHidden = function(isLast) {
if (isLast) $scope.hidden = false;
else $scope.hidden = true;
}
然后你将ng-class
添加到你的div:
<div class="optionary" ng-class="{'hidden': hidden}">...</div>
答案 1 :(得分:1)
您需要使用ng-show和控制变量。看一看。
jsFiddle这里:https://jsfiddle.net/U3pVM/24834/
<div ng-app class="labels" ng-controller="MyCtrl">
<div class="checkbox-element" ng-repeat="suggestName in suggests" ng-click="toggleSelection(suggestName, suggestsSelection, this)">
<label>
<input type="checkbox" ng-model="cbSuggest[$index]" name="suggestsSelection[]" class="hidden" value="{{suggestName}}">
<span>{{suggestName}}</span>
</label>
</div>
<div class="optionary hidden" ng-show="showOther">
<br>
<div class="question__text">Any other?</div>
<label><input type="text" ng-model="survey.suggest_other" name="suggests_other1"></label><br>
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.survey = {};
$scope.suggests = ['quality', 'price', 'habbit', 'other'];
$scope.cbSuggest = [];
$scope.showOther = true;
// selected
$scope.survey.suggestsSelection = [];
// toggle selection for a given names
$scope.toggleSelection = function(value, array, scope) {
var showOther = true;
angular.forEach($scope.cbSuggest, function(k,v){
if(k) {
showOther = false;
}
});
$scope.showOther = showOther;
};
}