在Angular中没有ngclick或ngsubmit事件时调用$ http

时间:2015-05-18 20:45:25

标签: angularjs

我无法弄清楚为什么我的两个控制器中的$http服务会在移动到相关路由时被触发。我尝试在这些控制器中创建其他功能,但这些功能没有被解雇,所以我怀疑这与$ http有关。 Doe控制器中的$http服务总是在实例化控制器时被解雇?我的目标是确保使用ng-click和ng-submit等指令触发postreq函数,而不是在实例化时。

这是我的代码:

mainCtrl.js

angular.module('LiveAPP.main', [])
    .controller('mainCtrl', ['$scope', '$http', '$location', mainCtrl]);

function mainCtrl($scope, $http, $location) {
    $scope.funcCheck = function() {
        console.log("this is firing")
    }

    $scope.postreq = $http({
        method: "post",
        url: "/",
        data: {
            user: "Junior",
            password: "Thisispassword"
        }
    }).success(function() {
        console.log("User posted to the database")
    });
}

signUpCtrl.js

angular.module('LiveAPP.signUp', [])
    .controller('signUpCtrl', ['$scope', '$http', signUpCtrl]);

function signUpCtrl($scope, $http) {
    $scope.number = 100;
    $scope.funcCheck = function() {
        console.log("this is firing")
    }
    $scope.postreq = $http({
        method: "post",
        url: "/",
        data: {
            user: "Junior",
            password: "Thisispassword"
        }
    }).success(function() {
        console.log("User posted to the database")
    });
};

的index.html

<!doctype html>
<html> 
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
    </script>
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/styles.css">


  </head>
  <body ng-app='LiveAPP'>
    <div ng-view></div>
    <script src="/controllers/mainCtrl.js"></script>
    <script src="/controllers/signUpCtrl.js"></script>
    <script src="/routes.js"></script> 
  </body>

</html>

routes.js

angular.module('LiveAPP', ['ngRoute','LiveAPP.main','LiveAPP.signUp'])

.config(function($routeProvider, $httpProvider) {
$routeProvider
  .when('/', {
    templateUrl : '/home.html',
    controller  : 'mainCtrl'
  })
  .when('/signup',{
    templateUrl : '/signup.html',
    controller  : 'signUpCtrl'
  })

});

1 个答案:

答案 0 :(得分:2)

我建议使用服务/工厂来处理任何$ http请求,但在你的情况下,是的,你需要把它放在一个函数中,因为此刻它被立即调用。

$scope.postreq = function() {
    $http({
        method: "post",
        url: "/",
        data: {
            user: "Junior",
            password: "Thisispassword"
        }
    }).success(function() {
        console.log("User posted to the database")
    });
}