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

时间:2015-08-14 17:30:09

标签: 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);
    }

})();

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

0 个答案:

没有答案