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");
});
也移除了,要如何移除指令時連同它的監聽也去掉呢?
漂亮男人2017-05-16 13:22:19
呼叫 $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();
});
}
阿神2017-05-16 13:22:19
指令:
var clear = scope.$watch("insert",function(n){
console.log("asd");
element[0].innerHTML = n;
});
$scope.$on('$destroy', function() {
clear();
});