$watch 事件不会在最初不可见的元素上触发
$watch event not triggering on element which is initially invisible
我有一个 angular ui 日期选择器元素,它最初是隐藏的,我想检测它的日期变化。
<div ng-if="titleVisible">
<input type="text" readonly
class="form-control"
datepicker-popup="{{format}}" ng-model="dt"
is-open="mydp.opened" editable="false"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
ng-required="true"
/> <span>
<button type="button" class="btn btn-default"
ng-click="openDate($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
我定义了这个观察者:
$scope.$watch(function(scope) { return scope.dt },
function(newValue, oldValue) {
if(oldValue != newValue) //needed to avoid call on init
console.log('dt has changed from '+oldValue+' to '+newValue);
}
);
此观察器从不触发,控制台日志从不显示。
无论如何,通过从组件定义中删除那个 ng-if (从而使其最初可见)它可以工作。
如何解决?
ng-if
创建一个子作用域。当您尝试从父范围查看 name
时,它看不到更改,因为 name
是在 ng-if
.
的子范围中创建的
一个解决方案是在父作用域中初始化一个对象,然后使 dt
成为该对象的 属性。
app.controller('MainCtrl', function($scope) {
$scope.myObj = {};
$scope.$watch('myObj.dt', function(newValue, oldValue) {
if(oldValue != newValue) //needed to avoid call on init
console.log('dt has changed from '+oldValue+' to '+newValue);
});
});
HTML
<div ng-if="titleVisible">
<input type="text" readonly
class="form-control"
datepicker-popup="{{format}}" ng-model="myObj.dt"
笨蛋:http://plnkr.co/edit/UmXqZDshVHOOLVYzZRZp?p=info
使用 ng-hide
而不是 ng-if
也应该有效。
我有一个 angular ui 日期选择器元素,它最初是隐藏的,我想检测它的日期变化。
<div ng-if="titleVisible">
<input type="text" readonly
class="form-control"
datepicker-popup="{{format}}" ng-model="dt"
is-open="mydp.opened" editable="false"
datepicker-options="dateOptions"
date-disabled="disabled(date, mode)"
ng-required="true"
/> <span>
<button type="button" class="btn btn-default"
ng-click="openDate($event)">
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
我定义了这个观察者:
$scope.$watch(function(scope) { return scope.dt },
function(newValue, oldValue) {
if(oldValue != newValue) //needed to avoid call on init
console.log('dt has changed from '+oldValue+' to '+newValue);
}
);
此观察器从不触发,控制台日志从不显示。 无论如何,通过从组件定义中删除那个 ng-if (从而使其最初可见)它可以工作。 如何解决?
ng-if
创建一个子作用域。当您尝试从父范围查看 name
时,它看不到更改,因为 name
是在 ng-if
.
一个解决方案是在父作用域中初始化一个对象,然后使 dt
成为该对象的 属性。
app.controller('MainCtrl', function($scope) {
$scope.myObj = {};
$scope.$watch('myObj.dt', function(newValue, oldValue) {
if(oldValue != newValue) //needed to avoid call on init
console.log('dt has changed from '+oldValue+' to '+newValue);
});
});
HTML
<div ng-if="titleVisible">
<input type="text" readonly
class="form-control"
datepicker-popup="{{format}}" ng-model="myObj.dt"
笨蛋:http://plnkr.co/edit/UmXqZDshVHOOLVYzZRZp?p=info
使用 ng-hide
而不是 ng-if
也应该有效。