javascript - 带有 this 关键字的 Angular $on 函数

标签 javascript angularjs

(function(){

    var eateryControllers=angular.module('eateryControllers',[]);

    eateryControllers.controller('MainController',function($scope){
        var mainCtrl=this;
        mainCtrl.$on('$viewContentLoaded',function(){
            console.log("view loaded");
        })
    });

})();

这导致错误:mainCtrl.$on 不是函数。早期版本通过注入(inject) $scope 来做到这一点。我们不能像上面那样使用“this”关键字和“Controller as”方法来做到这一点

最佳答案

在您的情况下,“this”指的是 Controller 而不是 $scope。要使“this”引用 $scope,您需要位于 $scope 方法内。您需要使用:

$scope.$on(...)

另请参阅:'this' vs $scope in AngularJS controllers

关于javascript - 带有 this 关键字的 Angular $on 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33180870/

相关文章:

javascript - 计算价目表+2/5商品后折扣

javascript - 如何从 ngRepeat 中的文本输入获取项目编号?

javascript - 我刚刚使用 gruntjs 构建了 AngularJS 项目,但是当我在浏览器中加载结果时,我得到一个空白页面,如何开始调试它?

javascript - JQuery 的 ajax 可以通过 https 发送客户端证书吗?

javascript - CKEditor 5 粘贴为纯文本

javascript - 具有授权过程的 AngularJS 路由

javascript - Angular 1 : Change title depending on current route

angularjs - 如何将数组发送到 API 调用中以设置对象列表 - Angular

javascript - 使用基本身份验证的跨域 AJAX?

javascript - 当我在任何浏览器中将 bot 框架 v4 与 js 集成时,LUIS 不起作用