我想将用户活动发送到服务器。在我的my previous question中,我问ng-click
案例。这个问题是关于复选框和单选按钮的情况。
我想向服务器发送用户点击用户活动的复选框或单选按钮。
我知道我可以这样做。
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 :(得分:0)
直接使用ng-click
,而不是使用摘要循环,只在点击事件时执行
答案 1 :(得分: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
}
如果您从复选框组或单选按钮组中调用相同的功能,您将获得一个不同的item
解析到该功能,然后您可以使用验证(类型检查)并获得您的相关数据。
您不需要以这种方式编写任何$watch
,因为ng-change
指令已经为您包装了一个。您需要拥有ng-model
。