您的位置:首页技术文章
文章详情页

javascript - angularjs 怎样移除指令监听?

【字号: 日期:2024-03-08 16:38:05浏览:29作者:猪猪

问题描述

angular移除指令内容后,它的监听还在控制器的 $scope 上,要怎样移除呢?代码如下:

<!DOCTYPE html><html><head> <meta charset='utf-8'> <script src='http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js'></script></head><body><p ng-app='myApp' ng-controller='myCtrl'> <p id='content'><span-c insert='name'></span-c> </p> <button ng-click='del()'>删除内容</button> <button ng-click='info()'>查看作用域</button> 输入内容: <input ng-model='name'></p><script> var app = angular.module(’myApp’, []); app.controller(’myCtrl’, function ($scope, $compile) {$scope.name = 'John Doe';$scope.$watch('xxx',function(){ console.log('xxx');});$scope.del = function () { document.getElementById('content').innerHTML = '';}$scope.info = function () {// $scope.$$watchers = []; console.log($scope.$$watchers);} }); app.directive('spanC', spanC); // 指令 function spanC() {return { restrict: 'AE', template: ’’, scope:{insert:'=' }, link: function (scope, element, attrs) {scope.$watch('insert',function(n){ console.log('asd'); element[0].innerHTML = n;}); }} }</script></body></html>

如果我直接

$scope.$$watchers = [];

把控制器上的

$scope.$watch('xxx',function(){ console.log('xxx');});

也移除了,怎样才能移除指令时连同它的监听也去掉呢?

问题解答

回答1:

调用 $scope.$watch() 或 $scope.$on() 方法后,都会返回一个函数引用,用于移除监听。了解详细信息,可以查看 Angular $rootScope 官方文档。另外若想了解 $broadcast、$on、$emit 使用方法,可以参考 - angularjs的事件 $broadcast and $emit and $on 这篇文章。

$scope.del = function () { document.getElementById('content').innerHTML = ''; $scope.$broadcast(’destroySpan’);};// spanC 指令link函数link: function (scope, element, attrs) { var unwatch = scope.$watch('insert',function(n){ console.log('asd'); element[0].innerHTML = n; }); scope.$on(’destroySpan’, function() { unwatch(); });}回答2:

指令:

var clear = scope.$watch('insert',function(n){ console.log('asd'); element[0].innerHTML = n;});$scope.$on(’$destroy’, function() { clear();});

标签: JavaScript
相关文章: