Reputation: 6612
I have an angular ui datepicker element which is initially hidden and whose I want to detect date change.
<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>
I have this watcher defined:
$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);
}
);
this watcher never triggers and the console log never shows. Anyway, by removing that ng-if from component definition (thus making it initially visible) it works. How to solve this?
Upvotes: 0
Views: 269
Reputation: 1729
ng-if
creates a child scope. When you are trying to watch name
from the parent scope, it does not see the changes because name
gets created in the child scope of ng-if
.
One solution would be to initialize an object in the parent scope, and then make dt
a property of that.
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"
Plunker: http://plnkr.co/edit/UmXqZDshVHOOLVYzZRZp?p=info
Using ng-hide
instead of ng-if
should also work.
Upvotes: 1