javascript - How to remove command listening in angularjs?
黄舟
黄舟 2017-05-16 13:20:19
0
2
695

After angular removes the directive content, its monitoring is still on the $scope of the controller. How to remove it?
code show as below:

<!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>

If I directly

$scope.$$watchers = [];

Put the

on the controller
$scope.$watch("xxx",function(){
            console.log("xxx");
        });

has also been removed. How can I remove the command along with its monitoring?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
漂亮男人

Call $scope.$watch()$scope.$on() 方法后,都会返回一个函数引用,用于移除监听。了解详细信息,可以查看 Angular $rootScope 官方文档。另外若想了解 $broadcast、$on、$emit For usage methods, please refer to - angularjs events $broadcast and $emit and $on this article.

$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();
     });
}
阿神

Command:

var clear = scope.$watch("insert",function(n){
    console.log("asd");
    element[0].innerHTML = n;
});
$scope.$on('$destroy', function() {
    clear();
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template