Javascript 什么';这两段代码之间的区别是什么?
我在Coursera上一门关于AngularJS的课程 讲师在视频中演示的代码有效,但由于某些原因,我无法在我的环境中运行: 页面布局(部分): 当我运行这个函数时,我在控制台中没有得到任何错误,但在显示中没有得到任何东西 片段B:Javascript 什么';这两段代码之间的区别是什么?,javascript,angularjs,Javascript,Angularjs,我在Coursera上一门关于AngularJS的课程 讲师在视频中演示的代码有效,但由于某些原因,我无法在我的环境中运行: 页面布局(部分): 当我运行这个函数时,我在控制台中没有得到任何错误,但在显示中没有得到任何东西 片段B: var app = angular.module('confusionApp',[]); app.controller('dishDetailController', function($scope) { var dish={ //attributes here;
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function($scope) {
var dish={ //attributes here;};
$scope.dish = dish;
});
当我这样做的时候,它是有效的。有什么不同吗?第二个片段(B)或多或少是直接从文档中提取出来的,很可能就是您要查找的
在代码段A中,通过this
分配值将直接将该值应用于控制器本身。这将使得在其他环境中很难访问,而且很可能不是您想要的
相反,代码段B利用AngularJS提供的依赖注入来确保将适当的范围注入方法$scope
的生命周期要复杂得多,但需要注意的是,这将使dish
在控制器的上下文之外可用,例如在HTML模板中
如果你需要更多的细节,这个人有一个更好的答案:检查这个代码,它正在工作
{{dish.name}
{{dish.label}
{{dish.price}}
{{dish.description1}}
var-app=angular.module('confusionApp',[]);
应用程序控制器('dishDetailController',函数($scope){
var dish={label:'name',name:'afzal',price:'10',description1:'这是价格'};
$scope.dish=dish;
});
由于控制器的连接方式,代码段A很可能无法工作。我在胡乱猜测
在添加ng控制器的地方,它可能看起来像:
<body ng-controller="dishDetailController as dish">
否则,您可能必须在模板内编写:{{{dish.dish.stuff}
。代码段A无效。您需要将控制器依赖项传递到函数中。不确定答案,但我对此也有疑问,并最终在使用$scope时实现了标准化。
这两个示例都是有效的。唯一的区别取决于您在视图中引用控制器的方式。与$scope相比,controller仅仅是一个区别,我能够让这个版本正常工作(即在函数中使用$scope)。这很有效。控制器本身在div中:我必须键入{{ddc.dish.}才能正确显示它。我想我困惑的一个原因是过度使用了“dish”。。。谢谢你的帮助!
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function($scope) {
var dish={ //attributes here;};
$scope.dish = dish;
});
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>
<body ng-controller="dishDetailController as dish">
<body ng-controller="dishDetailController">
var app = angular.module('confusionApp',[]);
app.controller('dishDetailController', function() {
this = {//attributes here}
});