我想使用$ watch以便在每次更改其中一个值时触发一个函数:
HTML:
<input type="hidden" name="source_x" id="source_x" ng-model="source_x"/>
<input type="hidden" name="source_y" id="source_y" ng-model="source_y"/>
<input type="hidden" name="id" id="id" ng-model="id"/>
我刚刚开始角度,我想使用$ watch来触发一个功能。 每次使用下面的可拖动功能拖动一个div时,这些值都会改变:
$("#div").draggable({
helper : 'clone',
stop:function(event,ui) {
var wrapper = $("#container-emote").offset();
var borderLeft = parseInt($("#container-emote").css("border-left-width"),10);
var borderTop = parseInt($("#container-emote").css("border-top-width"),10);
var pos = ui.helper.offset();
$("#source_x").val(pos.left - wrapper.left - borderLeft);
$("#source_y").val(-(pos.top - wrapper.top - borderTop)+185);
$("#id").val(2);
}
});
我从这开始,但我认为这是不对的,因为如果我移动一个div,我将调用3次函数?而且我不知道我是否可以使用它隐藏输入..谢谢!
//Fonction
$scope.$watch($scope.source_x, createEmote);
$scope.$watch($scope.source_y, createEmote);
$scope.$watch($scope.id, createEmote);
function createEmote(newValue, oldValue, scope){
}
更新:回答小提琴 我只是在拖动停止结束时添加一个函数
答案 0 :(得分:1)
您需要使用$scope.$watch
,如此:
$scope.$watch(function() {
return $scope.source_x + $scope.source_y + $scope.id;
}, function() {
$scope.createEmote();
});
让您的createEmote
成为$scope
的一个功能:
$scope.createEmote = function() {
// do something with $scope.source_x, etc
}
修改强>
如@Sergey的评论中所述,确切的观察者功能将取决于您的预期数据。如果需要,您也可以复制它并更改返回的变量(与现有代码类似)。