这两个 Angular 代码片段有什么区别?
这两个 Angular 代码片段有什么区别?
这个问题在这里已经有了答案:
我正在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日
第二个代码片段(B)基本上是直接从文档https://docs.angularjs.org/guide/controller中而来,很可能是你要找的。
在代码片段A中,通过this
分配一个值将直接应用于控制器本身。这将使其在其他上下文中非常难以访问,很可能不是你想要的。
相反,代码片段B利用了AngularJS提供的依赖注入,以确保正确的作用域注入到方法中。 $scope
具有更复杂的生命周期,但重要的是要注意这将使dish
在控制器之外的上下文中可用,例如在HTML模板中。
如果您需要更多细节,这个人有一个更好的答案:'this' vs $scope in AngularJS controllers