AngularJS module: this versus $scope

AngularJS module: this versus $scope

本文关键字:scope versus this module AngularJS      更新时间:2023-09-26

我是AngularJS的新手。我想知道两者之间有什么区别以下两个代码片段:

I。使用以下代码定义控制器:

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

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

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

谢谢。

这两个实现在视图中的使用方式不同。this语法与控制器一起使用作为句法,这本质上使您的控制器成为您的视图模型。

控制器为例

在控制器中

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/

"this"指的是HelloCtrl的实例。。。$scope是一个完全不同的对象,它已经获得状态,并通过角度进行管理