Angularjs - $ $范围破坏不会删除观察家 [英] Angularjs - $scope.$destroy doesn't remove watchers

查看:195
本文介绍了Angularjs - $ $范围破坏不会删除观察家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何创建自己的一次性绑定,为Angularjs< = 1.2。
我发现这个回答,描述了如何创建自己的bindOnce指令。我确实看到使用以下指令时:

I am trying to figure out how to create my own "one time binding", for Angularjs <= 1.2. I found this answer, describing how to create your own bindOnce directive. I do see that when using the following directive:

    app.directive('bindOnce', function() {
    return {
            scope: true,
            link: function( $scope ) {
                setTimeout(function() {
                    $scope.$destroy();
                }, 0);
            }
        }
    });

数据绑定一次。 但是上,我可以看到$$观察家还亮着。看看下面的 JSBin - 运行评论观察家计数在控制台上code就会发现,在观察家还活着。

Data is binded once. But, I can see that the $$watchers is still on. Take a look at the following JSBin - running the commented watcher count code on the console will reveal that the watchers are still alive.

修改:出于某种原因,使用具有角1.3相同的指令时,观察者计数mod改为0!

EDIT: for some reason, when using the same directive with angular 1.3, the watcher count dod changed to be 0!!!

推荐答案

使用清除函数删除观察家:

function cleanup(element) 
  { 
  element.off().removeData();

  var injector = currentSpec.$injector;

  element.$injector = null;

  // clean up jquery's fragment cache
  angular.forEach(angular.element.fragments, function(val, key) {
    delete angular.element.fragments[key];
  });

  angular.forEach(angular.callbacks, function(val, key) 
    {
    delete angular.callbacks[key];
    });

  angular.callbacks.counter = 0;
  }

使用自毁服务作为一个简单的绑定一次:

Use a self-destructing service as a simple bind once:

function onetime()
  {
  /*...*/
  onetime = Function;
  }

angular.module('myApp').constant('bindonce', onetime);

angular.module('myApp').controller('foo', function($bindonce){
  this.$inject = '$bindonce';
  $scope.mybind = $bindonce();
} 

使用,以供参考迁移指南找到突破的变化:

Use the migration guide for reference to find breaking changes:

参考

角mocks.js

AngularJS开发指南:从previous版本迁移

这篇关于Angularjs - $ $范围破坏不会删除观察家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆