2015-09-09 32 views
0

我有一個角度ui datepicker元素,它最初是隱藏的,我想檢測日期變化。

<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(從而使其初始可見),它就可以工作。 如何解決這個問題?

回答

1

ng-if創建子範圍。當您試圖從父作用域中觀察name時,它看不到更改,因爲nameng-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" 

Plunker:http://plnkr.co/edit/UmXqZDshVHOOLVYzZRZp?p=info

使用的ng-hide代替ng-if也應該工作。