我尝试使用以下代码从我的 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/