【问题标题】:Using $scope and 'this' in the controller with Angular UI Router在带有 Angular UI 路由器的控制器中使用 $scope 和“this”
【发布时间】:2015-10-25 15:01:37
【问题描述】:

关于$scopethis在使用ui-router时,

如果我使用controllerAs 语法,即:

.config(['$stateProvider', function($stateProvider) {
    $stateProvider
        .state('app.login', {
            url: '/login',                  
            templateUrl: 'modules/login/login.html',
            controllerAs: 'login',
            controller: 'LoginCtrl',
            data: {
                authorizedRoles: [USER_ROLES.all]
            }
        });
}])

然后,在我的控制器中,我使用this 而不是$scope。所以我的登录控制器中有这样的代码:

this.func1 = func1;
this.func2 = func2;
this.message = "Hello world!";

但我也使用$scope 来收听来自我的$rootScope 的全球广播事件,因为如果我没记错的话,this 没有属于$scope 的方法,即使它们正在互换.

$scope.$on('event', handler);

所以我正在收听$rootScope 广播的事件,并在广播此事件时调用其他一些控制器逻辑,例如func2

$scope.$on('auth-login-failed', function(event) {
// call some other function in controller
});

如果我想在$on 处理程序中调用func2 怎么办?我应该做一些约定,在我的控制器中初始化这样的东西吗?

var that = this;

$scope.$on('auth-login-failed', function(event) {
    this.func2();
});

我只是想知道最好的方法以及这里的一般约定是什么。 $scopethis 同时使用是否合适,两者之间的主要区别是什么,因为它们可以互换?

【问题讨论】:

  • 已经有多篇文章详细描述了这里的差异......本质上,$scope 总是存在,并且使用 ControllerAs 将控制器创建为 $scope 上的属性.至于在回调中引用控制器,使用别名或使用.bind() 都是可行的,并且与 Angular 本身相比,JavaScript 闭包的问题更多。 技术上,可以参考$scope.login.func2()

标签: angularjs angularjs-scope angular-ui-router angular-controller


【解决方案1】:

您的建议,也将逻辑上下文保留在某个变量中 - 非常好,也是很好的做法:

var _this = this;

$scope.$on('auth-login-failed', function(event) {
    _this.func2();
});

事实上,这就是 Typescript 在幕后为我们做同样事情的方式。它被称为

Arrow function

在打字稿中看起来像这样:

$scope.$on('auth-login-failed', (event) => {
    this.func2();
});

因为幕后的 Typescript 编译器将执行上述技巧,并将逻辑范围保存在某个变量中。

我建议你:

...尽量开始使用Typescript。 无论如何这都是角世界的未来......

有一些链接指向如何在Typescript 中创建 Angular 的controller,包括工作示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2021-05-31
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多