小问题,我可能真的很蠢,但我有一个网页的2个按钮,应该联系服务器。但是,只有第一个在按下时发送HTTP请求。
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('buttonApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myFunc = function(url) {
console.log("func called");
$http({
method: 'POST',
url: url,
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(response) {
console.log("Failed connection");
});
}
});
</script>
<body>
<div ng-app="buttonApp" ng-controller="myCtrl">
<button ng-click="myFunc('/buttonPressed1')">b1</button>
</div>
<div ng-app="buttonApp" ng-controller="myCtrl">
<button ng-click="myFunc('/buttonPressed2')">b2</button>
</div>
</body>
</html>
这是服务器代码。
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
var button = true;
app.use(function (req, res, next) {
req.testing = 'device-protocol';
return next();
});
app.get('/', function(req, res){
console.log('get route', req.testing);
res.sendFile( __dirname + "/" + "button.htm" );
});
app.post('/buttonPressed1', function(req, res){
//do some stuff
console.log("Button 1 pressed");
res.send("success");
});
app.post('/buttonPressed2', function(req, res){
//do some stuff
console.log("Button 2 pressed");
res.send("success");
});
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Test server listening at http://%s:%s", host, port)
})
答案 0 :(得分:1)
根据 Docs ,Angular应用不能有两个 ng-app
和 ng-controller
,有一个模块和控制器如下,
<body ng-app="buttonApp" ng-controller="myCtrl">
<div >
<button ng-click="myFunc('/buttonPressed1')">b1</button>
</div>
<div>
<button ng-click="myFunc('/buttonPressed2')">b2</button>
</div>
</body>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('buttonApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myFunc = function(url) {
console.log("func called"+url);
}
});
</script>
<body ng-app="buttonApp" ng-controller="myCtrl">
<div>
<button ng-click="myFunc('/buttonPressed1')">b1</button>
</div>
<div ng-app="buttonApp" ng-controller="myCtrl">
<button ng-click="myFunc('/buttonPressed2')">b2</button>
</div>
</body>
</html>