Javascript Deep$watch AngularJS系列
这是我的目标:Javascript Deep$watch AngularJS系列,javascript,angularjs,angularjs-scope,watch,Javascript,Angularjs,Angularjs Scope,Watch,这是我的目标: $scope.steps = { service: { selected_service: '', selected_month: '', selected_year: '', selected_day: '' }, payment: { selected_dd_type: '', cc:
$scope.steps = {
service: {
selected_service: '',
selected_month: '',
selected_year: '',
selected_day: ''
},
payment: {
selected_dd_type: '',
cc: {
selected_card_type: '',
credit_card_number: '',
name_on_card: '',
expiry_month: '',
expiry_year: ''
},
bank_acc: {
bsb_number: '',
account_number: '',
account_holder_name: ''
}
},
agreement: {
agreement_acceptance: false
}
}
以下是$watchCollection
:
$scope.$watchCollection('steps.service', function(newVal, oldVal) {
$scope.canExit = true;
});
$scope.$watchCollection('steps.payment', function(newVal, oldVal) {
$scope.canExit = true;
}, true);
$scope.$watchCollection('steps.payment.cc', function(newVal, oldVal) {
$scope.canExit = true;
}, true);
$scope.$watchCollection('steps.payment.bank_acc', function(newVal, oldVal) {
$scope.canExit = true;
}, true);
$scope.$watchCollection('steps.agreement', function(newVal, oldVal) {
$scope.canExit = true;
}, true);
一切正常
必须有更好的方法查看$scope.steps
对象。
如果我执行$watch
步骤
它将不起作用。我想我看得不够深
$scope.$watchCollection('steps', function(newVal, oldVal) {
$scope.canExit = true;
}, true);
谢谢你的指导。给你。将值
true
作为$watch
中的第三个选项传递:
$scope.$watch('steps', function(newValue, oldValue) {
// callback on deep watch
$scope.canExit = true;
}, true);
此外,请确保在手表内添加if
条件,因为将值分配给$scope.steps
时也会触发手表
工作示例:
var-app=angular.module(“sa”,[]);
应用控制器(“FooController”,功能($scope){
$scope.canExit=false;
$scope.steps={
服务:{
所选的\u服务:“”,
所选月份:“”,
所选年份:“”,
所选日期:“”
},
付款:{
所选的\u dd\u类型:“”,
抄送:{
所选的\u卡\u类型:“”,
信用卡号码:'',
卡上的名称:“”,
到期月份:'',
到期年:''
},
银行账户:{
bsb_编号:“”,
账号:'',
帐户\持有人\名称:“”
}
},
协议:{
接受协议:错误
}
};
$scope.reset=函数(){
$scope.canExit=false;
}
//使用Math.random()只是为了演示,以便可以调用手表
$scope.changeService=函数(){
$scope.steps.service.selected_service=Math.random();
}
$scope.changeDate=函数(){
$scope.steps.payment.cc.selected_card_type=Math.random();
}
$scope.changeAgreement=函数(){
$scope.steps.agreement.agreement_acceptance=Math.random();
}
$scope.$watch('steps',函数(newValue,oldValue){
if(newValue&(newValue!==oldValue)){
//深度监视回调
$scope.canExit=true;
}
},对);
});代码>
换乘服务
更改有效期
变更协议
可以退出:{canExit}
重置
1)正如caramiriel在评论中发布的那样,您可以将$watch与函数参数一起使用
$watch(
function(){
var calculatedVal = /*make all required checks*/;
return calculatedVal;
},
function(newVal){
$scope.canExit = true;
}
);
2) 更好的选择是完全避免观看,并使用事件/回调(如ng更改);它更出色,更容易阅读 谢谢你,伙计。这就成功了。那么为什么步骤上的$watchCollection
不起作用呢?即使我将true
标志添加到$watchCollection
。首先,不接受任何第三个参数,因此传递任何内容都不会产生任何效果:)并且文档中说$watchCollection
浅层监视对象的属性,因此它在casesHmmm中不起作用。再次感谢。我认为这个问题是另一个问题的重复。我现在可能会标记它。干杯。是的,这是我标记的问题的副本。很高兴您发现它是重复的:)