简体   繁体   English

为什么它可以与$ scope一起使用但不能与`this`一起使用?

[英]Why does it work with $scope but not with `this`?

I want to know why the following only works with the scripts 1 and 3 and not with the 2. I want to use this because in my project I can't use $scope. 我想知道为什么以下仅适用于脚本1和3而不适用于2。我想使用它,因为在我的项目中我不能使用$ scope。

Thank you!! 谢谢!!

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script> <!DOCTYPE html> <!-- --> <html ng-app="app"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script> <meta charset="utf-8"> <title>Modelo</title> </head> <body> <div ng-controller="AppCtrl"> Nombre: {{ name}} <script type="text/javascript"> var app=angular.module("app",[]); function AppCtrl($scope) { $scope.name= "Bob"; } </script> </div> <br/> <div ng-controller="MyCtrl"> Nombre: {{ name }} <script type="text/javascript"> var app= angular.module("app",[]); var MyCtrl = function() { this.name = 'Nico'; } app.controller('MyCtrl',MyCtrl); </script> </div> <br/> <div ng-controller="Algo as and"> Nombre: {{and.name}} <script type="text/javascript"> //angular.controller('Algo',Algo); function Algo() { var vm = this; vm.name = "Nicolas"; } </script> </div> </body> </html> 

If it's hard to understand please tell me. 如果很难理解,请告诉我。

And forgive me for my English. 并请原谅我的英语。

ng-controller uses constructor function of the controller. ng-controller使用ng-controller构造函数。 In 1st and 3rd cases, we have constructor functions to controllers. 在第一种和第三种情况下,我们为控制器提供了构造函数。 But in second case its just a variable. 但是在第二种情况下,它只是一个变量。 So, it will not work. 因此,它将无法正常工作。

ng-controller="myCtrl" when you define something like this, angular tries to find the constructor function of the myctrl . ng-controller="myCtrl"定义类似这样的内容时,angular试图找到myctrl的构造函数。 If, function myCtrl(){} is there, it works fine. 如果function myCtrl(){}存在,则可以正常工作。 That is what happening in 1st and 3rd case. 这就是在第一和第三种情况下发生的情况。

The extra use of $scope than this is when there are event watchers. 在有事件监视程序的情况下, $scopethis更多使用。 But we can avoid them. 但是我们可以避免它们。 for more info https://johnpapa.net/do-you-like-your-angular-controllers-with-or-without-sugar/ You can get idea which one to use. 有关更多信息, 请参见https://johnpapa.net/do-you-like-your-angular-controllers-with-or-without-sugar/您可以了解要使用哪一个。

To access this over $scope , you must use the controller as syntax , which is what your third example does. 要通过$scope来访问this ,必须使用controller作为语法 ,这是您的第三个示例所做的。 But the usage may vary a little, see the doc link above for example code. 但是用法可能会有所不同,请参见上面的doc链接以获取示例代码。

This post talks of the advantages of the controller as syntax in real development, you may want to take a look. 这篇文章谈到了控制器在实际开发中作为语法的优势,您可能想看看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM