【问题标题】:AngularJS $watch not working in if-blockAngularJS $watch 在 if-block 中不起作用
【发布时间】:2016-04-09 00:09:52
【问题描述】:

我发现我的 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

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

【问题讨论】:

  • ng-if 创建她自己的范围,所以 DatePicker 在控制器的范围内无效
  • 只要你不改变 if 语句中的 DatePicker,它们是同步的......所以,sope 似乎是一样的
  • 这就是原型继承的工作原理:您可以读取父属性,但是当您尝试写入时 - 您创建自己的属性而不是更改父属性

标签: javascript angularjs if-statement angularjs-scope angularjs-watch


【解决方案1】:

来自doc

此指令创建新范围。

所以,在你的情况下

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多