angularjsangularjs-ng-clickangular-controller

ng-click doesn't invoke method inside angularJs controller


I am trying to create an angular application from scratch. I have been trying to solve this for hours now, but I couldn't make it work. All the following files are placed inside a parent folder.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Hello</title>
  <script data-require="angular.js@1.6.0" data-semver="1.6.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <h1>Student App</h1>
  <section ng-controller="HelloController">
    <h4>Enter Student Details</h4>
    <label for="name">Name :</label>
    <input id="name" type="text" ng-model="student.name" />
    <p>Hello {{student.name}}!</p>
  </section>
  <button id="name" type="submit" ng-click="onButtonClick()">Click</button>

</body>

</html>

HelloController.js

  angular.module('app', [])
    .controller('HelloController', ["$scope", function($scope) {

    $scope.onButtonClick = function()
    {
        console.log("method invoked");
    };

}]);

It would be nice if someone could help me solve this problem I am facing.


Solution

  • Your button is out of the <section> controlled by the controller. So clicking on it calls onButtonClick() on the root scope, not on te controller's scope.