1

I have HTML code with ng-click event:

<div class="btn share" ng-click="do($event)">
   <span">1</span>
</div>

Angular JS:

$scope.do = function (event) {
  var target = angular.element(event.target);
  var parsed = parseInt(target.find('span').text(), 10);
}

When I click to element div or child element span is called event do(). But if I click on span my counter inside span is not increment. Only by clicking parent element div. How I can set same $event for div and span elements?

1
  • <span">1</span> is that " a typo or your error? Commented Sep 5, 2015 at 9:10

3 Answers 3

4

I would recommend to work with scope bindings instead of DOM textContent:

<div class="btn share" ng-click="do()">
   <span>{{count}}</span>
</div>

and in controller

$scope.count = 0;
$scope.do = function () {
    $scope.count++;
};

If you however still want to know why it failed with your approach, it's because you need to use currentTarget, not just target:

angular.module('demo', []).controller('MainCtrl', function($scope) {
    $scope.do = function(event) {
        var target = angular.element(event.currentTarget);
        var parsed = parseInt(target.find('span').text(), 10);
        target.find('span').text(parsed + 1);
    };

});
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>

<div ng-app="demo" ng-controller="MainCtrl" class="btn share" ng-click="do($event)">
    <span>1</span>
</div>

But don't do this, controller should not work with DOM at all, this is not what controllers are for.

Sign up to request clarification or add additional context in comments.

Comments

1

You're doing it the wrong way. Angular is not jQuery. You shouldn't do any DOM manipulation in the controller. The view should be generated based on the model, and not vice-versa.

The code should be

<div class="btn share" ng-click="do()">
    <span>{{ counter }}</span>
</div>

and in the controller:

$scope.counter = 1;
$scope.do = function() {
    doSomethingWithCounter($scope.counter);
}

Comments

1

Have you tried adding the same click event to your span also?

Like this

<span ng-click="do($event)"> 1 </span>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.