angularjs controllersAs注册$destroy
发布时间:2020-12-17 07:47:13 所属栏目:安全 来源:网络整理
导读:有角度的文档说,为了在控制器销毁时执行代码进行清理,应该在范围上注册$destroy事件. $scope.$on("$destroy",function() { ... } ); 但是,当您使用controllerAs语法时,您无权访问$scope.你如何注册$destroy事件? 只是因为你使用controllerAs语法,并不意味着
有角度的文档说,为了在控制器销毁时执行代码进行清理,应该在范围上注册$destroy事件.
$scope.$on("$destroy",function() { ... } ); 但是,当您使用controllerAs语法时,您无权访问$scope.你如何注册$destroy事件?
只是因为你使用controllerAs语法,并不意味着没有$scope或者你不能使用它.
实际上,所有的控制器都是将控制器添加到$scope(指定的名称下).例如.: ng-controller="SomeCtrl as ctrl" 会隐含地这样做: .controller('SomeCtrl',function () { this.value = 'something'; ... // Angular will implicitly so something equivalent to: // $scope.ctrl = this; } 所以,没有什么可以阻止你使用$范围(实际上对于观看东西和发送/监听事件这样的事情非常有用): <!-- In the VIEW --> <div ng-controller="SomeCtrl as ctrl"> Some value: {{ctrl.value}} <button ng-click="ctrl.doSomething()">Some action</button> </div> /* In the CONTROLLER */ .controller('SomeCtrl',function ($scope) { this.value = 'some value'; this.doSomething = function () { ... }; $scope.$on('$destroy',function () { // So some clean-up... }); }); 另见这个short demo. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |