这两个 Angular 代码片段有什么区别?

13 浏览
0 Comments

这两个 Angular 代码片段有什么区别?

这个问题在这里已经有了答案

\'this\' vs $scope in AngularJS controllers

我正在Coursera上学习AngularJS。

讲师在视频中演示的代码能够运行,但由于某些原因,我无法在我的环境中运行:

网页布局(局部):

{{dish.name}} {{dish.label}} {{dish.price | currency}}

 

{{dish.description}}

 

片段A(教授演示,我无法让其运行):

var app = angular.module('confusionApp',[]);        
app.controller('dishDetailController', function() {
var dish={ //attributes here; };
this.dish = dish;
});

当我运行这个函数时,控制台不会出现任何错误,但在显示中也没有任何结果。

片段B:

var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function($scope) {
var dish={ //attributes here;};
$scope.dish = dish;
});

以这种方式进行操作,它可以正常工作。有区别吗?

admin 更改状态以发布 2023年5月23日
0
0 Comments

第二个代码片段(B)基本上是直接从文档https://docs.angularjs.org/guide/controller中而来,很可能是你要找的。

在代码片段A中,通过this分配一个值将直接应用于控制器本身。这将使其在其他上下文中非常难以访问,很可能不是你想要的。

相反,代码片段B利用了AngularJS提供的依赖注入,以确保正确的作用域注入到方法中。 $scope具有更复杂的生命周期,但重要的是要注意这将使dish在控制器之外的上下文中可用,例如在HTML模板中。

如果您需要更多细节,这个人有一个更好的答案:'this' vs $scope in AngularJS controllers

0
0 Comments

Snippet A无法正常工作,很可能是因为控制器的连接方式不正确。这里我只是猜测。

在添加ng-controller时,它应该是这样的:

 

而你可能是这样的:

 

也可能不是body标签,可能是一个div或其他什么。

为了在Snippet A控制器中更好地理解,尝试:

var app = angular.module('confusionApp',[]);        
app.controller('dishDetailController', function() {
    this = {//attributes here}
});

否则你可能要在模板中写{{dish.dish.stuff}}

0