AngularJS-$ scope.$ destroy不会删除观察者 [英] Angularjs - $scope.$destroy doesn't remove watchers

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

问题描述

我正在尝试找出如何为Angularjs< = 1.2创建自己的一次性绑定".我找到了这个 answer ,描述了如何创建自己的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 -运行评论的观察者在控制台上计数代码将显示观察者还活着.

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.

编辑:由于某些原因,当使用与angular 1.3相同的指令时,观察者计数的dod更改为0!

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

推荐答案

使用 cleanup 函数删除观察者:

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:

参考

angular-mocks.js

AngularJS开发人员指南:从早期版本的迁移

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

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