2016-12-03 60 views
0

小問題,我可能真的很笨,但我有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) 
}) 

回答

1

根據Docs,角應用不能有兩個ng-appng-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>

+0

不只**不需要**,**是**不能**。 Angular不允許有兩個'ng-app'副本。 – Claies

+0

@Claies多數民衆贊成我提到的相同的東西 – Sajeetharan

+0

你說「不需要」,這是不一樣的「不能有」。我認爲它可能會更清楚一點,它根本不可能。 – Claies

相關問題