我想使用 $watch 以便每次这 3 个值之一发生更改时触发一个函数:
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"/>
我刚刚开始使用 Angular,我想使用 $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){
}
更新:回答 fiddle 我只是在拖动停止的末尾添加一个函数
最佳答案
您需要像这样使用您的$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 的评论中所指出的,确切的观察器功能将取决于您的预期数据。如果需要,您也可以复制它并更改返回的变量(类似于您现有的代码)。
关于javascript - AngularJs 值更改时隐藏输入的调用函数 $watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168062/