AngularJS$watch在if块中不工作

AngularJS $watch not working in if-block

本文关键字:工作 if watch AngularJS      更新时间:2023-09-26

我发现,我的角度脚本正在工作:

$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

但我不明白为什么。是否存在已知问题?有人能帮忙吗?

来自文档

此指令创建新的作用域。

所以,在你的情况下

<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>

或应用"点规则"

<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>