我想知道如何在$watch
表达式中触发第二个摘要周期。似乎在$watch
表达式中,只有一个摘要周期是可能的。我试着打电话给$apply
,但它崩溃了“消息已经在进行中”。
function TestCtrl($scope) {
var purchase_orders = [
{id : 1, name : 'Purchase Order One', multiple_day_rates : true },
{id : 2, name : 'Purchase Order Two', multiple_day_rates : false },
{id : 3, name : 'Purchase Order Three', multiple_day_rates : true } ];
$scope.purchase_orders = purchase_orders;
$scope.$watch(
"poId",
function( poId ) {
console.log("watch triggered for po id");
$scope.multiple_day_rates = null; //seems to have no effect..
//$scope.$apply(function () {
// $scope.multiple_day_rates = null;
// }); --> throws digest already in progress
var purchase_order_obj = jQuery.grep($scope.purchase_orders, function(e){ return e.id == $scope.poId; });
if(typeof purchase_order_obj[0] != 'undefined'){
if(purchase_order_obj[0].multiple_day_rates == true){
console.log("before setting multiple day rates to true");
$scope.multiple_day_rates = true;
}
else{
console.log("before setting multiple day rates to false");
$scope.multiple_day_rates = false;
$scope.day_rate_check=true;
}
}
}
);
$scope.$watch(
"multiple_day_rates",
function( multiple_day_rates ) {
console.log("watch triggered for multiple day rates");
}
);
}
我的目标是在设置$scope.multiple_day_rates
时,我想运行一些代码。我还想检测它何时从true
设置为true
。由于AngularJS正在进行某种脏检查(仅在值发生变化时触发监视),我必须先将$scope.multiple_day_rates
设置为null,以便检测到更改。但不知何故,似乎在$watch
表达式中只有一个摘要周期是可能的。这是JSFiddle。您可以看到当选择从“采购订单一”更改为“采购订单二”时没有任何反应,因为multiple_day_rates
在两个时间true
内都没有。
答案 0 :(得分:1)
这是你想要实现的目标吗?
function TestCtrl($scope, $timeout) {
var purchase_orders = [{
id: 1,
name: 'Purchase Order One',
multiple_day_rates: true
}, {
id: 2,
name: 'Purchase Order Two',
multiple_day_rates: false
}, {
id: 3,
name: 'Purchase Order Three',
multiple_day_rates: true
}];
$scope.purchase_orders = purchase_orders;
$scope.$watch(
"poId",
function (poId) {
console.log("watch triggered for po id");
$scope.multiple_day_rates = null; //seems to have no effect..
//$scope.$apply(function () {
// $scope.multiple_day_rates = null;
// }); --> throws digest already in progress
$timeout(function () {
var purchase_order_obj = jQuery.grep($scope.purchase_orders, function (e) {
return e.id == $scope.poId;
});
if (typeof purchase_order_obj[0] != 'undefined') {
if (purchase_order_obj[0].multiple_day_rates == true) {
console.log("before setting multiple day rates to true");
$scope.multiple_day_rates = true;
} else {
console.log("before setting multiple day rates to false");
$scope.multiple_day_rates = false;
$scope.day_rate_check = true;
}
}
});
}
);
$scope.$watch(
"multiple_day_rates",
function (multiple_day_rates) {
console.log("watch triggered for multiple day rates");
}
);
}