javascript - angularjs 怎樣移除指令監(jiān)聽?
問題描述
angular移除指令內(nèi)容后,它的監(jiān)聽還在控制器的 $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()'>刪除內(nèi)容</button> <button ng-click='info()'>查看作用域</button> 輸入內(nèi)容: <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');});
也移除了,怎樣才能移除指令時連同它的監(jiān)聽也去掉呢?
問題解答
回答1:調(diào)用 $scope.$watch() 或 $scope.$on() 方法后,都會返回一個函數(shù)引用,用于移除監(jiān)聽。了解詳細(xì)信息,可以查看 Angular $rootScope 官方文檔。另外若想了解 $broadcast、$on、$emit 使用方法,可以參考 - angularjs的事件 $broadcast and $emit and $on 這篇文章。
$scope.del = function () { document.getElementById('content').innerHTML = ''; $scope.$broadcast(’destroySpan’);};// spanC 指令link函數(shù)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();});
相關(guān)文章:
1. javascript - 最近用echarts做統(tǒng)計圖時遇到兩個問題!!2. 淺談Vue使用Cascader級聯(lián)選擇器數(shù)據(jù)回顯中的坑3. android - 使用MTP連接的時候如何使自己的app加入選擇列表4. 利用IPMI遠程安裝centos報錯!5. angular.js - angular ng-focus ng-blur 存在問題6. 為什么redis中incr一個“0” 會報錯?7. celery+redis 怎么看redis里面的內(nèi)容8. android - 使用百度sdk調(diào)用SDKInitializer.initialize(this)時報錯?9. android - TextInputLayout的空白顯示問題10. android - 優(yōu)酷的安卓及蘋果app還在使用flash技術(shù)嗎?

網(wǎng)公網(wǎng)安備