Search code examples
javascriptangularjsangularjs-ng-clickangularjs-ng-include

ng-click does not trigger the function associated with it?


I am having troubles with using ng-click. I have added ng-click directive to the button. It does not trigger the function associated with ng-click. In Angular Batarang tool, it says the functions are undefined.

I tried the problem in Plunker.It does work. And also If i hard code the file path it works.

index.html code

<!DOCTYPE html> 
<HTML ng-app="myEventApp">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
            <h1 ng-controller="HelloWorldController">{{ helloMessage }}</h1>
            <div ng-controller="EventDetail">
            </div>
            <div ng-include="" src="fileName"></div>
            <!--<ng-include src="fileName"></ng-include>-->
            <!--<div ng-include="" src="'template/testing10000.html'"></div>-->
            <button ng-click=incrementCounter()>Next</button>
            <button ng-click=decrementCounter()>Back</button>
            <script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
            <script src="js/app.js"> </script>
    </body>
</HTML>

app.js code

var app = angular.module("myEventApp", []);

app.controller('HelloWorldController', ['$scope', function($scope){
        $scope.helloMessage = "Book Viewer";
}]);


app.controller('EventDetail', ['$scope', function($scope){

        $scope.counter = 0;
        $scope.fileName = 'template/testing1000'+$scope.counter+'.html';


        $scope.incrementCounter = function(){
              $scope.counter++;
              $scope.fileName = 'template/testing1000'+$scope.counter+'.html';
              console.log($scope.counter);
        }

        $scope.decrementCounter = function(){
              $scope.counter--;
              $scope.fileName = 'template/testing1000'+$scope.counter+'.html';
              console.log($scope.counter);
        }


}]);

Solution

  • You declared the functions inside the EventDetail controller, but you have the buttons outside of the controller container in the html.

    <div ng-controller="EventDetail">
        <div ng-include="" src="fileName"></div>
    
        <button ng-click="incrementCounter()">Next</button>
        <button ng-click="decrementCounter()">Back</button>    
    </div>