【问题标题】:AngularJS module: this versus $scope [duplicate]AngularJS 模块:this 与 $scope [重复]
【发布时间】:2014-12-31 16:58:55
【问题描述】:

我是 AngularJS 的新手。我想知道有什么区别 以下两个代码sn-ps:

我。使用此定义控制器的代码:

var app = angular.module('greeting', []);
app.controller('HelloCtrl', function() {
  this.name = 'Hello World';
});

二。使用 $scope 定义控制器的代码:

var app = angular.module('greeting', []);
app.controller('HelloCtrl', function($scope) {
  $scope.name = 'Hello World';
});

谢谢。

【问题讨论】:

    标签: javascript angularjs scope angularjs-scope this


    【解决方案1】:

    这两种实现在视图中的使用方式不同。 this 语法与 controller as 语法一起使用,这实际上使您的控制器成为您的视图模型。

    以控制器为例

    在控制器中

    this.text = "Controller as example"
    

    在视图中

    <div ng-controller="myCtrl as controllerViewModel">
        {{controllerViewModel.text}}
    </div>
    

    作用域等效

    在控制器中

    $scope.text = "Scope example";
    

    在视图中

    <div ng-controller="myCtrl">{{text}}</div>
    

    这里有一些关于该主题的有用链接

    https://docs.angularjs.org/api/ng/directive/ngController

    http://toddmotto.com/digging-into-angulars-controller-as-syntax/

    https://thinkster.io/egghead/experimental-controller-as-syntax/

    【讨论】:

      【解决方案2】:

      'this' 指的是 HelloCtrl 的实例... $scope 是一个完全不同的对象,它已经有了状态并通过 angular 进行管理

      【讨论】:

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