Angular 一次性有条件地绑定或在设置特定值时取消绑定侦听器

Angular One-time bind conditionally OR unbind listener when a specific value is set

我在 DOM 中有如下内容:

 <div ng-if="variant"
    ng-include="'size-picker.html'">
 </div>

在控制器中:

$scope.variant = false;
// after some unknown time there may be:
$scope.variant = true;

我想证明 div 当 variant 为真时。所以,

$scope.variant 将从 false 开始。一段时间后它 may/may 没有变成 true。当 $scope.variant 变成 true 时,它永远不会改变它的值。所以我想要的是一次性绑定 ng-if 一旦 $scope.varianttrue.

像这样的方法:

<div ng-if="::variant"
    ng-include="'size-picker.html'">
</div>

为假时将停止绑定。

我可以通过第一次停止将false分配给variant来实现,但在我的情况下这是不可能的。

varianttrue 时,如何取消绑定 ng-if?

文档说:

One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value.

所以你可以从一个未定义的值开始。

您可以使用 $watch,注销 bindingscope

$watch returns 一个 deregistration 函数。

您可以使用 $watch 调用返回的函数注销 $watch

var unwatch = $scope.$watch('variant', function(newValue, oldValue) {
    if(newValue == true)
    {
        unwatch();
    }
});

因此,一旦您的变体变为真,其上的手表将被移除,绑定将停止。

var app = angular.module( "Demo", [] );

app.controller(
  "AppController",
  function( $scope ) {
    $scope.count = 0;
    $scope.after_unwatch = false;

    var unbindWatcher = $scope.$watch(
      "count",
      function( count ) {
        alert( "Watching click count." );
        if ( count >= 5 ) {
          $scope.after_unwatch = true;
          unbindWatcher();
        }

      }
    );


  
    $scope.incrementCount = function() {
      $scope.count++;
    };

  }
);
<html>
<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <div  ng-app="Demo" ng-controller="AppController">
    <h1>
      Unbinding $watch() Listeners In AngularJS
    </h1>

    <p>
      <a ng-click="incrementCount()">Click it for five times, and after that watch on `count` is removed.</a>
      &raquo;

    </p>

    <p ng-show="after_unwatch">
      <em>The watch on click is removed.</a>
    </p>
  </div>
 </body>
</html> 

运行这个代码

Here is a plunker