Angular js: how to use ngMousedown ngMouseup

2019-06-26 03:13发布

Is it possible to use ngMousedown for adding class to a div and ngMouseup for removing the class again? At the moment I use ng-mousedown="activateClass()" , in activateClass() change $scope.className="data-active" and change it again with other function with ng-mouseup. And use ng-class to add the class "data-active" I don't wanna use $scope.className and change it with function in controller, because this function is used for several divs and I don't want to add the class to all of the divs I have.

Thank you.

4条回答
我命由我不由天
2楼-- · 2019-06-26 04:01

did you mean this:

<div ng-mousedown="upordown='down'" 
     ng-mouseup="upordown=''" 
     ng-class="upordown">content</div>
查看更多
我命由我不由天
3楼-- · 2019-06-26 04:03

You can use ng-events with ng-class to achieve it:

<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-animate.min.js"></script>
</head>
<body>
<input type="button" value="click me" ng-mousedown="className='data-active'" ng-mouseup="className=''">
<br>
<span class="base-class" ng-class="className">Sample Text</span>
</body>
</html>
查看更多
混吃等死
4楼-- · 2019-06-26 04:06

Normally controllers should not care about your DOM. What you are trying to do there seems more like suitable for a directive. I would implement a directive:

app.directive("highlight", function() {
  return function(scope, element, attrs) {
    element.on('mouseup', function(event) {
      element.removeClass(attrs.highlight)
    })
    element.on('mousedown', function(event) {
      element.addClass(attrs.highlight)
    })
  }
})

and use it on a div like this

 <div highlight="active">
      my content is here
 </div>

where as active is the name of my css class.

查看更多
萌系小妹纸
5楼-- · 2019-06-26 04:07

If you don't want to use controller, you may just write ng-mousedown="className='data-active'" in your view

查看更多
登录 后发表回答