I am trying to build an angular app and recently I have one problem.
I have something like this
<div ng-class="{selectThis : item.pick}" ng-click="pickItem(item)" class="item">Item name here<div>
JS controller:
$scope.pickItem = function(item) {
item.pick = true;
}
Css:
.item {
color: red;
…more css
}
.item:hover {
color:blue;
...more css
}
.selectThis {
color:blue;
}
It works well on desktop but the hover effect will remain on touch device when user touches the div. I know I can add the media query to solve this but I think that's a outdated approach. Is there anyways I can solve it with Angular way? Thanks a lot!
You could solve it with Angular by adding a class when a touch events are fired:
app.directive('touchClass', function() {
return {
restrict: 'A',
scope: {
touchClass: '@'
},
link: function(scope, element) {
element.on('touchstart', function() {
element.$addClass(scope.touchClass);
});
element.on('touchend', function() {
element.$removeClass(scope.touchClass);
});
}
};
});
Then you can add this directive to any element you want. It will add the touch
class whilst there is a touch in progress and it will remove it when the touch is over.
<div ng-class="{selectThis : item.pick}"
ng-click="pickItem(item)"
touch-class="touch"
class="item">
Item name here
<div>
You can treat this class almost like the hover pseudo selector:
.item {
color: red;
…more css
}
.item.touch {
color:blue;
...more css
}
.selectThis {
color:blue;
}
You can also do something on the touch events:
<div ng-class=="{ 'touch': touchStart}"
on-touch
class="item">Item name here<div>
And make a directive which handles the touch event
.directive('onTouch',function() {
return {
restrict: 'A',
link: function ($scope, $elem, $attrs) {
$elem.on('touchstart',function(e) {
$scope.touchStart= true;
$scope.$apply();
});
$elem.on('touchend',function(e) {
$scope.touchStart= false;
$scope.$apply();
});
}
}
});
PD: i didn't try this code, is just a draft. I hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.