0

If I have 2 divs (removed ng-click function for simplicity)

<div ng-class="{selected: header.type == 'percent'}" data-type="percent"></div>
<div ng-class="{selected: header.type == 'invisible'}" data-type="invisible"></div>

This will apply the class of .selected to one of the divs, depending on the value of $scope.header.type

However, I also have it so when I click on the div that does not have the .selected class, i remove the selected class from the div that had it, and apply it to the div that was just clicked.

Now, on the controller, how do I get the data-type of the div that has the .selected class?

Basically I'm trying to set $scope.header.type to hold the value of data-type of the div that has the .selected class

Just in case it's needed, here's the ng-click fn (which is not angular-like, but I couldn't find an alternative)

$scope.changeOfferbox = function($event) {
    var selected  = angular.element(document.querySelector('.selected'))
    selected.removeClass('selected')
    var clicked = angular.element($event.target).addClass('selected')
}

1 Answer 1

1

A simple solution might be to pass the data-type to your click function ; this way, you actually don't even need to manually add/remove classes, the ng-class directives will automatically update when header.type changes :

$scope.changeOfferbox = function($event, localType) {
    if (localType !== $scope.header.type) {
        $scope.header.type = localType;
    }
};

<div ng-class="{selected: header.type == 'invisible'}" ng-click="changeOfferbox('invisible');" data-type="invisible"></div>
2
  • This didn't work for me (localType would pass as undefined). Ended up using ng-click="changeOfferbox($event.target)", and inside the ng-click fn, i grab data-type with var type = element.attributes['data-type'].value
    – sqram
    Oct 5, 2014 at 22:27
  • I forgot $event in the call, sorry. Glad you worked it out anyway !
    – Sycomor
    Oct 6, 2014 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.