在控制器上的这个和范围的区别 [英] Difference between this and scope in the controller

查看:141
本文介绍了在控制器上的这个和范围的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来angularjs。
是什么如果您分配的功能$范围或该关键字控制器的区别?
谢谢。

例(范围):

  .controller('TestCtrl',['$范围',函数($范围){
    $ scope.testFunc =功能(){
    };
}]);

示例()

  .controller('TestCtrl',[功能(){
    VAR应用=这一点;
    app.testFunc =功能(){
    };
}]);


解决方案

$范围是角框架和双数据绑定functionnalities的一个核心概念。它例如,旨在分享其内容:


  • 模板

  • 指令


在例如模板,你需要绑定到的范围访问它的功能。你不能叫绑定一个函数这个直接


编辑:感谢访问 BKM帖子该人士指出,这种行为是可能的控制器语法,直接与您的模板到控制器。但它是由你来决定,如果你想要让访问你的模板控制器的所有对象/变量,而无需专门的视图模型范围)。对于利弊,请参见:<一href=\"https://groups.google.com/forum/#!topic/angular/84selECbp1I\">https://groups.google.com/forum/#!topic/angular/84selECbp1I


这是你需要了解角的一个重要概念。

请参阅:

这个 keywork指只有JavaScript的对象指的是你的控制器,仅此而已。

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

Example (scope):

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

Example (this)

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

解决方案

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

  • templates
  • directives
  • etc

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.


Edit: 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.

See :

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

这篇关于在控制器上的这个和范围的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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