Reputation: 110
I have a dinamically builded list of tests:
<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>
and I want to add a class to the div(class="test") in which button was pressed.
I am familiar only with the jQuery and I can think of only this approach:
$scope.processAnswer = function(isRight, event) {
isRight ? $scope.count++ : $scope.count--;
event.target.parentNode.parentNode.parentNode.addClass('hide');
}
How to do it in Angular style ?
EDIT: My solution:
<div ng-class="($index==selectedIndex) ? 'hide' : 'test'" ng-repeat="test in tests">
controller:
$scope.selectedIndex = -1;
$scope.processAnswer = function(isRight, index) {
isRight ? $scope.count++ : $scope.count--;
$scope.selectedIndex = index - 1; //$index starts at 0;
}
where index
is test.number
Upvotes: 0
Views: 5376
Reputation: 89
Try as simple
$element.parent().addClass('default-class');
Upvotes: 0
Reputation: 25352
Try like this
angular.element(event.target).parent().parent().addClass("hide");
Manipulating dom in html is not recommended . You should do your dom manipulation only in directives.
Upvotes: 3
Reputation: 727
You could maybe use ng-class
to apply the class when you set a boolean to true
. For example :
<div class="test" ng-repeat="test in tests" ng-class="{'hide' : onProcessAnswer}">
and in your controller
$scope.onProcessAnswer = false;
$scope.processAnswer = function(isRight, event) {
...
$scope.onProcessAnswer = true;
...
}
Upvotes: 1
Reputation: 120
In my opinion, Angular is a library to make coders do less dom option.
You can use data-bind feature to achieve most request mostly.
If you do want to get a parent element and add an attribute, just use jQuery or pure javascript.
Upvotes: 0