我有一个恐怖的测试列表:
<script id="TestsTemplate" type="text/ng-template">
<article class="tests-main">
<section class="tests">
<div class="test" ng-repeat="test in tests">
<p>Question {{ test.number }}:</p>
<div ng-repeat="answer in test.answers">
<div ng-repeat="(key, value) in answer">
<p><button ng-click="processAnswer(value, $event)" class="btn" >○ {{ key }}</button></p>
</div>
</div>
</div>
</article>
</script>
我想在div(class =“test”)中添加一个类,按下按钮。
我只熟悉jQuery,我只能想到这种方法:
$scope.processAnswer = function(isRight, event) {
isRight ? $scope.count++ : $scope.count--;
event.target.parentNode.parentNode.parentNode.addClass('hide');
}
如何以Angular风格完成?
修改 我的解决方案:
<div ng-class="($index==selectedIndex) ? 'hide' : 'test'" ng-repeat="test in tests">
控制器:
$scope.selectedIndex = -1;
$scope.processAnswer = function(isRight, index) {
isRight ? $scope.count++ : $scope.count--;
$scope.selectedIndex = index - 1; //$index starts at 0;
}
其中index
为test.number
答案 0 :(得分:3)
试试这个
angular.element(event.target).parent().parent().addClass("hide");
不建议在html中操作dom。你应该只在指令中进行dom操作。
答案 1 :(得分:1)
当您将布尔值设置为ng-class
时,您可以使用true
来应用该类。例如:
<div class="test" ng-repeat="test in tests" ng-class="{'hide' : onProcessAnswer}">
并在您的控制器中
$scope.onProcessAnswer = false;
$scope.processAnswer = function(isRight, event) {
...
$scope.onProcessAnswer = true;
...
}
答案 2 :(得分:0)
在我看来,Angular是一个让编码人员做更少dom选择的库。
您可以使用数据绑定功能来实现大多数请求。
如果你想获得一个父元素并添加一个属性,只需使用jQuery或纯javascript。
答案 3 :(得分:0)
尝试简单
$element.parent().addClass('default-class');
&#13;