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

8

我正在Coursera上学习AngularJS课程。

讲师在视频中展示的代码可以运行,但出于某些原因,我不能在我的环境中运行:

页面布局(部分):

<div class="media-body">
<h2 class="media-heading">{{dish.name}}
<span class="label label-danger">{{dish.label}}</span>
<span class="badge">{{dish.price | currency}}</span></h2>
<p>{{dish.description}}</p>
</div>

Snippet A(由我无法工作的教授演示):

代码段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;
});

当我这样做时,它有效。有什么区别吗?


1
代码片段A是无效的。您需要将控制器依赖项传递到函数中。 - agconti
不确定答案,但我也遇到了这个问题,并最终统一使用$scope.<etc> - miltonb
1
这两个示例都是有效的。唯一的区别取决于您在“view”中如何引用控制器。这只是“controller as vs $scope”的微小差别。 - Rayon
3个回答

6

很可能Snippet A不起作用的原因是控制器的附加方式不正确。我只是猜测。

在添加ng-controller的位置,应该像这样:

 <body ng-controller="dishDetailController as dish">

相反,你可能会得到这个:

 <body ng-controller="dishDetailController">

可能不是body标签,而是div或其他标签。

为了更好地理解,在代码片段中尝试使用控制器:

var app = angular.module('confusionApp',[]);        
app.controller('dishDetailController', function() {

    this = {//attributes here}

});

否则,您可能需要在模板中编写:{{dish.dish.stuff}}

这个可以运行了。控制器本身在 div 中:<div class="row row-content" ng-controller="dishDetailController as ddc"> 我必须输入 {{ddc.dish.<attribute>}},使其正确显示。我想我的困惑之一是过度使用了“菜肴”这个词……感谢您的帮助! - THawk

1
第二个片段(B)基本上是直接从文档https://docs.angularjs.org/guide/controller中摘取的,很可能是您要找的。
在片段A中,通过this分配一个值将直接应用于控制器本身。这将使它非常难以在其他上下文中访问,并且很可能不是您想要的。
相反,片段B利用了AngularJS提供的依赖注入,以确保将适当的作用域注入到方法中。 $scope具有更复杂的生命周期,但需要注意的重要事项是,这将使dish在控制器之外的上下文中可用,例如在HTML模板中。
如果您需要更多详细信息,这位先生有一个更好的答案:'this' vs $scope in AngularJS controllers

0
chech this code it is working 

<div ng-app='confusionApp' ng-controller='dishDetailController' class="media-body">
<h2 class="media-heading">{{dish.name}}
<span class="label label-danger">{{dish.label}}</span>
<span class="badge">{{dish.price}}</span></h2>
<p>{{dish.description1}}</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js"></script>
<script type="text/javascript">

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

var dish={ label:'name',name:'afzal',price:'10',description1:'this is the price'};

$scope.dish = dish;
});
</script>

我已经成功让这个版本工作了(即在函数中使用 $scope)。 - THawk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接