ng-click不会触发与之关联的功能?

时间:2016-03-31 07:10:16

标签: javascript angularjs angularjs-ng-click angularjs-ng-include

使用ng-click时遇到麻烦。我在按钮上添加了ng-click指令。它不会触发与ng-click相关的功能。在Angular Batarang工具中,它表示函数未定义。

我在Plunker中尝试过这个问题。它确实有效。而且如果我硬编码文件路径它的工作原理。

index.html代码

<!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代码

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);
        }


}]);

1 个答案:

答案 0 :(得分:5)

您在EventDetail控制器中声明了这些函数,但是您在html中的控制器容器外面有按钮。

<div ng-controller="EventDetail">
    <div ng-include="" src="fileName"></div>

    <button ng-click="incrementCounter()">Next</button>
    <button ng-click="decrementCounter()">Back</button>    
</div>