0

I am trying to update the value of a variable in the scope within a directive and then I expect to see the value changed in the html. However, it is not what happens in the example below.

When you press button 1 everything is correct, but when you press button 2 the value is not directly updated, although the counter is increased (you can see it by pressing button 1 again).

js:

angular.module('app', [])
.controller('AppCtrl', function($scope) {
 $scope.count = 0;
 $scope.plus = function() {
 $scope.count += 1;
 };
})
.directive('dir', function() {
 return {
 restrict: 'A',
 scope: {
 count: '=',
 plus: '&'
 },
 link: function(scope, element, attrs, ctrl) {
 element.on('mousedown', function(event) {
 scope.plus();
 scope.count += 1;
 });
 }
 }
});

html:

<div ng-controller="AppCtrl">
<h2> {{count}} </h2>
<button ng-click="plus()"> 1 </button>
<button dir count="count" plus="plus()"> 2 </button>
</div>

Try it: http://jsfiddle.net/k6chmnch/311/

asked Jun 11, 2015 at 13:25

2 Answers 2

1

Try:

element.on('mousedown', function(event) {
 scope.$apply(function(){
 scope.count += 1; 
 })
});
answered Jun 11, 2015 at 13:28
Sign up to request clarification or add additional context in comments.

2 Comments

Great! It did it! Why is that? In fact, if you modify the scope.counter outside the element.on function it works, why isn't it working inside without the apply?
You're going to excuse my language, but this is because "Angle" always running "$ apply" on their own policies or events. See a similiar question
0

The fist thing I see is that you are invoking plus rather than passing in a reference. Get rid of the parens in the HTML:

<button ng-click="plus"> 1 </button>
<button dir count="count" plus="plus"> 2 </button>
answered Jun 11, 2015 at 13:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.