Brittany
Brittany

Reputation: 362

Function in AngularJS controller not being called

I am trying to call a function from my AngularJS controller with the following code:

Controller Code

(function () {

    var hello = angular.module("helloApp", []);

    hello.controller("HelloCtrl", ["$http", "$scope", function($scope, $http) {
        console.log("in controller");
        $scope.test = function() {
            console.log("in test function");
            $http.get("/test").success(function(data) {
                console.log("success");
            })
            .error(function(data) {
                console.log("error");
            });
        };
    } ]);

})();

HTML

<!DOCTYPE html>
<html ng-app="helloApp">
  <head>
    ...
  </head>
  <body ng-controller="HelloCtrl">
  <div class="container">
    <form class="form-horizontal">
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" ng-click="test()">Search</button>
        </div>
      </div>
    </form>
  </div>
  ...
</body>

When I launch the application, I see the message "in controller", as I would expect. However, if I click on the submit button then I do not see any of the other three console messages.

What am I missing?

Upvotes: 2

Views: 7106

Answers (1)

Reactgular
Reactgular

Reputation: 54821

Your order of dependency injection is wrong.

hello.controller("HelloCtrl", ["$http", "$scope", function($scope, $http) {

Should be

 hello.controller("HelloCtrl", ["$http", "$scope", function($http, $scope) {

The order of parameters must be the same order as the array of names.

Upvotes: 5

Related Questions