AngularJS $观察不在if-block中工作

时间:2016-01-05 08:23:17

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

我发现,我的角色脚本正在运行:

$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-statment则不行:

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

试试吧: http://codepen.io/anon/pen/jWBEVM

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

1 个答案:

答案 0 :(得分: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>

或者应用&#34;点规则&#34;

<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

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

样品

&#13;
&#13;
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);

});
&#13;
<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>
&#13;
&#13;
&#13;