ibci
ibci

Reputation: 126

Scope binding within a directive

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/

Upvotes: 0

Views: 58

Answers (2)

BJ Safdie
BJ Safdie

Reputation: 3419

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>

Upvotes: 0

Try:

element.on('mousedown', function(event) {
   scope.$apply(function(){
     scope.count += 1;                
   })
});

Upvotes: 1

Related Questions