2017-08-24 46 views
0

我想将用户活动发送到服务器。在我的my previous question中,我询问了ng-click的情况。这个问题是关于复选框和单选按钮的情况。AngularJS:发送复选框/单选按钮值到服务器

我想发送到服务器哪个复选框或单选按钮用户点击记录用户活动。

我知道我可以这样做。

HTML:

<!-- for checkbox --> 
<div class="btn-group"> 
    <label class="btn btn-primary" ng-model="checkModel.left" uib-btn-checkbox>Left</label> 
    <label class="btn btn-primary" ng-model="checkModel.right" uib-btn-checkbox>Right</label> 
</div> 

<!-- for radio button--> 
<div class="btn-group"> 
    <label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Left'">Left</label> 
    <label class="btn btn-primary" ng-model="radioModel" uib-btn-radio="'Right'">Right</label> 
</div> 

JS:

$scope.$watch('checkModel', function() { 
    sendServer("checkModel" + JSON.stringify(checkModel)); 
    // Do other things for checkModel 
}, true); 

$scope.$watch('radioModel', function() { 
    sendServer("radioModel" + radioModel); 
    // Do other things for radioModel 
}); 

function sendServer(msg) { 
    var req = new XMLHttpRequest(); 
    var params = "msg=" + encodeURIComponent(msg); 
    req.open("POST", "/scripts/log"); 
    req.send(params); 
} 

这样要求我插入sendServer所有watch。这是低效的。我想以综合的方式来做。我可以做吗?

+0

您可以用'directive'这个 –

+0

你可以参考这里:https://stackoverflow.com/questions/45767704/angularjs-send-user-activity-to-server?noredirect=1&lq=1 –

+0

使用[AngularJS $ http服务](https://docs.angularjs.org/api/ng/service/$http)代替原始的'XMLHttpRequest'。 '$ http'服务是一个核心的AngularJS服务,它通过浏览器的[XMLHttpRequest API](https://developer.mozilla.org/en/xmlhttprequest)来促进与远程HTTP服务器的通信。 – georgeawg

回答

0

使用ng-click直接,这种方式而不是使用摘要循环,你只有在点击的情况下,执行

0

您可以使用ng-change运行有一个功能,并注入模型值,那么你可以做任何你要

<div class="btn-group"> 
    <label class="btn btn-primary" ng-model="checkModel.left" ng-change="run(checkModel)" uib-btn-checkbox>Left</label> 
    <label class="btn btn-primary" ng-model="checkModel.middle" ng-change="run(checkModel)" uib-btn-checkbox>Middle</label> 
    <label class="btn btn-primary" ng-model="checkModel.right" ng-change="run(checkModel)" uib-btn-checkbox>Right</label> 
</div> 

控制器:

$scope.run = function(item) { 
    console.log(item); // will print the model object 
    // run your sendServer function here 
} 
  1. 如果您从复选框组或单选按钮组中调用相同的功能,您将得到一个不同的item解析到该函数,然后可以使用验证(类型检查)并获取您的相关数据。

  2. 这种方式不需要编写任何$watch,因为ng-change指令已经为您包装了一个。您将需要有一个ng-model