angularjs – 如何使用Controller作为语法访问$on,$emit,$broadc
发布时间:2020-12-17 07:44:44 所属栏目:安全 来源:网络整理
导读:使用$scope可以轻松地发布一个事件或观看一个事件. (function() { "use strict"; angular .module("app") .controller("Ctrl",[ "$scope",CtrlDefinition ]); function CtrlDefinition($scope) { $scope.$on("change",listenForChange); function listenForC
使用$scope可以轻松地发布一个事件或观看一个事件.
(function() { "use strict"; angular .module("app") .controller("Ctrl",[ "$scope",CtrlDefinition ]); function CtrlDefinition($scope) { $scope.$on("change",listenForChange); function listenForChange(data) { //do something } } })(); 但是如果我尝试使用var vm =这个语法,我被警告说,$on,$emit和$broadcast不是这个方法.如何访问它们?我还需要在控件定义中注入$scope? (function() { "use strict"; angular .module("app") .controller("Ctrl",CtrlDefinition); function CtrlDefinition() { var vm = this; vm.$on("change",listenForChange); //$on is not a method of vm } })(); 你可以做这样的事情,但是不会破坏不必使用$scope的目的呢? (function() { "use strict"; angular .module("app") .controller("Ctrl",CtrlDefinition ]); function CtrlDefinition($scope) { var vm = this; vm.scope = $scope; vm.scope.$on("change",listenForChange); } })(); 如何使用控制器访问观察者作为语法?
为了使用$scope上存在的任何东西,您将被迫注入$scope.不幸的是,这是简单的,这是“as”语法的缺点.
不过,好消息是,与此同时注入$范围并不会改变控制器作为语法的功能,它只是让您访问生活在$scope上的所有事件管理. 值得注意的是,这是Angular 2.0中出现的主要原因之一… $scope与“Controller as”语法之间存在一个真正的问题和差异,这些语法被用来解决视图中的范围问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容