这与控制器中的作用域之间的区别 [英] Difference between this and scope in the controller

查看:25
本文介绍了这与控制器中的作用域之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angularjs 的新手.如果您将函数分配给 $scope 或控​​制器中的 this 关键字,有什么区别?谢谢.

I'm new to angularjs. What is the difference if You assign function to $scope or this keywords in the controller? Thank You.

示例(范围):

.controller('TestCtrl', ['$scope', function ($scope) {
    $scope.testFunc = function () {
    };
}]);

例子(这个)

.controller('TestCtrl', [function () {
    var app = this;
    app.testFunc = function () {
    };
}]);

推荐答案

$scope 是 Angular 框架和双重数据绑定功能的核心概念.例如,它旨在与以下人员共享其内容:

$scope is a core concept of angular framework and dual data-binding functionnalities. Its for example, designed to share its content with :

  • 模板
  • 指令

例如,在模板中,您需要将一个函数绑定到 scope 以访问它.您将无法直接调用绑定在 this 上的函数.

In a template for example, you'll need to bind a function to the scope to access it. You'll not be able to call a function binded on this directly.

感谢 BKM 帖子指出这种行为是可能的controller as"语法将您的模板直接绑定到控制器.但是由您决定是否要允许访问模板中控制器的所有对象/变量,而不是拥有专用的 viewModel(scope).有关利弊,请参阅:https://groups.google.com/forum/#!topic/angular/84selECbp1I

Thank to BKM post that pointed out that this behavior is possible with the "controller as" syntax which binds your template directly to the controller. But it's up to you to decide if you want to let access all objects/variables of your controller in your template instead of having a dedicated viewModel (scope). For pros and cons, see : https://groups.google.com/forum/#!topic/angular/84selECbp1I

您需要了解角度的​​一个重要概念.

It's an important concept of angular that you need to understand.

见:

  • http://docs.angularjs.org/guide/scope for an introduction
  • https://github.com/angular/angular.js/wiki/Understanding-Scopes for more technical information about scopes

this 关键字仅指代您的 controller 的 javascript object,仅此而已.

this keywork refers only the the javascript object refering to your controller, nothing more.

这篇关于这与控制器中的作用域之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆