小编典典

如何使用Controller作为语法访问$ on,$ emit,$ broadcast方法?

angularjs

使用$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 = this语法,我警告说$on$emit$broadcast不是的方法this。如何访问它们?我还需要注入$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", [
            "$scope",
            CtrlDefinition
        ]);

    function CtrlDefinition($scope) {
        var vm = this;
        vm.scope = $scope;
        vm.scope.$on("change", listenForChange);
    }

})();

如何使用控制器作为语法访问观察者?


阅读 395

收藏
2020-07-04

共1个答案

小编典典

为了使用存在的任何东西$scope,您不得不注入$scope。不幸的是,它很简单,这是“ as”语法的缺点。

不过,好消息是,$scope与之一起注入this不会改变控制器作为语法的功能,它只是使您能够访问存在于上的所有事件管理 $scope

值得注意的是,这是Angular 2.0中出现问题的主要原因之一…之间存在一个真正的问题和差异,$scope而用来解决视图范围问题的“
Controller as”语法也是如此。

2020-07-04