我有一个简单的输入字段更新变量鉴于:AngularJS:功能仅后事件发生
<input id = 'input' ng-model="addMe">
连接到的脚本:
<script>
document.getElementById('input').onkeydown = function(event) {
if (event.keyCode == 13) {
angular.element(document.getElementById('input')).scope().addItem();
}
}
</script>
即存在这样,无论何时用户按下输入字段; AngularJS中的addItem
函数将输入字段中的字符串添加到数组中。
$scope.addItem = function() {
found = false;
if (!$scope.addMe) return $scope.errorText = "Please Specify an Item";
else {
angular.forEach($scope.Products, function(value, key) {
if (value.name.toUpperCase() == $scope.addMe.toUpperCase()){
$scope.cart_items.push({name : value.name, price : value.price});
$scope.grandTotal += value.price;
$scope.addMe = '';
$scope.errorText = '';
found = true;
}
});
if(!found){$scope.errorText = "Item does not exist";}
}
}
注意cart_items
和products
是数组(不直接相关的问题)
当我按下回车,传递正确的变量函数addItem
被调用;但像errorText
,grandTotal
这样的变量,以及应该推入数组的数据只在我按另一个键或点击时更新。
我知道该功能正在做它应该做的事情;因为我用console.log
进行调试。
可能的问题的代码消化 – Groben