Arun P Johny
Arun P Johny

Reputation: 388436

Why this $apply in directive is throwing value undefined error

I'm trying write a directive using angular js, in which a button click has to increment a count value.

On the click event handler I'm trying to increment the value using the scope.$apply construct but it is throwing an Syntax Error: Token 'undefined' not a primary expression at column NaN of the expression [count++] starting at [count++] error in the console.

markup

<div ng-app="myApp">
    <div ng-controller="MainCtrl">
        <div my-directive >
        </div>
    </div>
</div>

JS

var myApp = angular.module('myApp', []);

myApp.directive('myDirective', function(){
    return {
        scope: {},
        template: '<div>{{count}}</div><input type="button" class="increment" value="Increment" />',
        link: function(scope, iElement, iAttrs, controller) {
            console.log('link', scope.count)
            iElement.on('click', '.increment', function(){
                console.log('click', scope.count);
                scope.$apply('count++');
            })
        },
        controller: function($scope){
            console.log('controller')
            $scope.count = 0;
        }
    };
});

myApp.controller('MainCtrl', ['$scope', function($scope){
}]);

Demo: Fiddle

Upvotes: 1

Views: 8806

Answers (2)

satchmorun
satchmorun

Reputation: 12477

Why not just use ng-click?

<body ng-controller='MainCtrl'>
  <button ng-click="increment()" value="Increment Me!">
  <h1>{{count}}</h1>
</body>

And in your JS:

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

Upvotes: 3

Michelle Tilley
Michelle Tilley

Reputation: 159135

Changing your expression to

count = count + 1

fixes the problem. Demo: Fiddle

Since Angular doesn't use eval to evaluate expressions, you cannot use quite the full range of JavaScript in them; this is one of those exceptions. If you do need something a bit more powerful, you can pass a JavaScript function to $apply (demo: Fiddle):

scope.$apply(function() {
  scope.count++;
});

Upvotes: 4

Related Questions