0

We have this square <div> element which has a specific class applied for style. Inside there's a vertically/horizontally aligned <span> element which has sprite class applied to show an image.

The square has a black background and the image is a flat yellow icon. The idea is to switch the colors when the user is touching the whole square (including the background and the image). For this we need to switch 2 classes, on for the outer <div> (to show a yellow background) and another for the inner <span> to display a black image from the sprite.

The problem is, how to achieve this with AngularJS and touch down and up events. We are using angular-touch but that simply overrides ngClick for a better implementation for mobile/touch devices and adds ngSwipeLeft and ngSwipeRight directives. Neither doesn't seem to really help with our issue.

What would be the best way to achieve this effect with AngularJS?

rfgamaral
  • 16,546
  • 57
  • 163
  • 275

1 Answers1

1

I would use a scope boolean value to indicate when the div is touched, based on javascript events touchstart and touchend, then have ng-class show the correct class based on that boolean. Example:

        <style>
            .color-white {
                color : white;
            }
            .background-green {
                background : green;
            }
        </style>

        <button my-touch="myIndicator"
            ng-class="{
                 'color-white'      : myIndicator,
                 'background-green' : myIndicator
            }">Touch this</button>

        .directive('myTouch',function() {
            return {
                link: function ($scope, $elem, $attrs) {
                    var _t = $attrs.myTouch;
                    $elem.on('touchstart touchend',function(e) {
                        $scope[_t] = (e.type === 'touchstart');
                        $scope.$apply();
                    });
                }
            }
        });
koolunix
  • 1,995
  • 16
  • 25