2015-05-18 27 views
0

我無法弄清楚爲什麼在我的兩個控制器中$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

您將需要移動'$ HTTP({...'中的特定功能.. – PSL

回答

2

我會建議使用任何$ HTTP請求的服務/工廠,但在你的情況下,是的,你需要把這個功能,因爲在目前它被立即調用。

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

感謝您的答覆。什麼是您使用的服務或工廠$ http請求提示的原因嗎? – theamateurdataanalyst

+0

它所有這些都取決於你計劃構建的應用程序的類型,以及數據是否將在多個控制器之間共享。引用,_「像這樣抽象$ http調用將允許你在多個控制器中重用這個代碼。當與這些數據交互的代碼變得更加複雜時,它變得有必要。「_你也可以利用使用承諾。 –