angularjs - AngularJS Controller 中的函数未被调用

标签 angularjs angularjs-controller angularjs-ng-click

我尝试使用以下代码从我的 AngularJS Controller 调用函数:

Controller 代码

(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>

当我启动应用程序时,我看到消息“在 Controller 中”,正如我所期望的那样。但是,如果我单击提交按钮,那么我看不到其他三个控制台消息中的任何一个。

我错过了什么?

最佳答案

您的依赖注入(inject)顺序错误。

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

应该是

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

参数的顺序必须与名称数组的顺序相同。

关于angularjs - AngularJS Controller 中的函数未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28822591/

相关文章:

facebook - og 元标签、社交按钮和 angularjs

javascript - 使用 Angular JS 通过 Rails Paperclip 提交文件

javascript - 如何使用ngdialog在angularjs中实现重定向之前的消息?

javascript - 在 ng-click 上设置并显示当前数据?

javascript - 在选择标签中使用 ng-click 的 Angular

javascript - html 中的条件语句

javascript - Python - selenium - AngularJS 下拉菜单,如何点击它们?

javascript - RequireJS 正在加载 Angular 应用程序,但不会创建 app.controller

javascript - 如何让 AngularJS 在 svg 模板中填充初始标签值?

javascript - 将 ng-click 绑定(bind)到动态数组上的 ng-repeat