在ng-click上调用一个函数

时间:2017-06-27 15:14:35

标签: angularjs angularjs-ng-click

<html>
<head>
<title>Javascript Login Form Validation</title>
<link rel="stylesheet" href="css/style.css"/> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
  <script>
function MyCtrl($scope){
    $scope.myval = 5;

    $scope.ctrlClickHandler = function(){
        alert("Inside controller: value of myval is " + $scope.myval);
    }       
};

var globalClickHandler=function globalClickHandler(){
    alert("Inside global click handler ");
}
</script>
</head>
<body>
<div class="container">
<div class="main" ng-app ng-controller="MyCtrl">
<form id="form_id" method="get" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username"/>
<label>Password :</label>
<input type="password" name="password" id="password"/>
<button type="button" ng-click="ctrlClickHandler()">Login</button>
</form></div></div></body></html>

这是我上面的代码,我无法调用ctrlClickHandler方法。我不知道我错了。任何人都可以帮助我。 提前谢谢!。

1 个答案:

答案 0 :(得分:1)

您需要定义angular.module才能使用angular

var globalClickHandler=function globalClickHandler(){
    alert("Inside global click handler ");
}

angular.module("app",[])
.controller("ctrl", MyCtrl)

 function MyCtrl($scope){
    $scope.myval = 5;

    $scope.ctrlClickHandler = function(){
        alert("Inside controller: value of myval is " + $scope.myval);
    }       
};
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="main" ng-app="app" ng-controller="MyCtrl">
<form id="form_id" method="get" name="myform">
<label>User Name :</label>
<input type="text" name="username" id="username"/>
<label>Password :</label>
<input type="password" name="password" id="password"/>
<button type="button" ng-click="ctrlClickHandler()">Login</button>
</form></div>