AngularJS $watch 在 if-block 中不工作

AngularJS $watch not working in if-block

我发现我的 angular 脚本正在运行:

$scope.CurrentUser = null;
$scope.DatePicker = new Date();
$scope.$watch('DatePicker', function (newValue, oldValue) {
    if (newValue > new Date())
        $scope.DatePicker = new Date();
}, true);
<div>
    <input data-ng-model="DatePicker" type="date" id="datepicker" />
</div>

但如果我添加 if 语句则不会:

<div data-ng-if="!CurrentUser">
    <input data-ng-model="DatePicker" type="date" id="datepicker" />
</div>

尝试一下: http://codepen.io/anon/pen/jWBEVM

但我不明白为什么。有已知问题吗?有人可以帮忙吗?

来自 doc

This directive creates new scope.

所以,在你的情况下

<div data-ng-if="!CurrentUser">
    <input data-ng-model="DatePicker" type="date" id="datepicker" />
</div>

DatePicker 此处添加在 ng-if 范围内,而不是来自控制器的范围。

求解可以用$parent属性

<div data-ng-if="!CurrentUser">
    <input data-ng-model="$parent.DatePicker" type="date" id="datepicker" />
</div>

或申请"dot rule"

<div data-ng-if="!CurrentUser">
    <input data-ng-model="data.DatePicker" type="date" id="datepicker" />
</div>

在 js 中

$scope.data = { DatePicker : new Date() };
$scope.$watch('data.DatePicker', function (newValue, oldValue) {
...

wiki

中查看更多关于继承范围的信息

样本

var app = angular.module('myApp', []);

app.controller('BodyCtrl', function($scope, $http) {
  $scope.CurrentUser = null;
  $scope.DatePicker = new Date();
  $scope.data = { DatePicker : new Date() } ;
  $scope.$watch('DatePicker', function(newValue, oldValue) {
    if (newValue > new Date())
      $scope.DatePicker = new Date();
  }, true);
  $scope.$watch('data.DatePicker', function(newValue, oldValue) {
    if (newValue > new Date())
      $scope.data.DatePicker = new Date();
  }, true);

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<div data-ng-app="myApp" data-ng-controller="BodyCtrl">
  <div>
    <span>scope id: {{$id}}</span>
    <input data-ng-model="DatePicker" type="date" id="datepicker" />
  </div>
  <div data-ng-if="!CurrentUser">
    <span>scope id: {{$id}}</span>
    <input data-ng-model="DatePicker" type="date"  />
  </div>
  <div data-ng-if="!CurrentUser">
    <span>scope id: {{$id}}</span>
    <input data-ng-model="$parent.DatePicker" type="date" />
  </div>
  <hr/>
  <div>
    <span>scope id: {{$id}}</span>
    <input data-ng-model="data.DatePicker" type="date" />
  </div>
  <div data-ng-if="!CurrentUser">
    <span>scope id: {{$id}}</span>
    <input data-ng-model="data.DatePicker" type="date"  />
  </div>
  
</div>