正在进行AngularJS的基本训练,但是首先陷入困境,表达式没有使用ng-controller
依赖进行评估。
的index.html
<html ng-app="store">
<head>
<title>Angular JS</title>
<link rel="Stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>{{"Hello"}}</h1>
<div ng-controller="StoreController as stores">
<h1> {{stores.products.name}} </h1>
<h2> {{stores.products.price}} </h2>
<p> {{stores.products.description}} </p>
</div>
</body>
</html>
app.js
(function () {
var app = angular.module("store", []);
app.controller = ('StoreController', function () {
this.products = gem;
});
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
HTML输出
Hello
{{stores.products.name}}
{{stores.products.price}}
{{stores.products.description}}
请帮我解决我的错误。
答案 0 :(得分:2)
这是更典型的,我会说最佳做法是在$scope
上设置任何数据。然后,您不必简单地使用控制器和参考产品的别名。您必须将$scope
注入控制器。代码看起来像:
<强>的index.html 强>
<html ng-app="store">
<head>
<title>Angular JS</title>
<link rel="Stylesheet" type="text/css" href="bootstrap.min.css" />
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<h1>{{"Hello"}}</h1>
<div ng-controller="StoreController">
<h1> {{products.name}} </h1>
<h2> {{products.price}} </h2>
<p> {{products.description}} </p>
</div>
</body>
</html>
<强> app.js 强>
(function () {
var app = angular.module("store", []);
app.controller('StoreController', ['$scope', function($scope) {
$scope.products = gem;
}]);
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
答案 1 :(得分:2)
您的控制器中的=符号不正确。
(function () {
var app = angular.module("store", []);
////NOT app.controller = ('StoreController'.....
app.controller('StoreController', function () {
this.products = gem;
});
var gem =
{
name:'New Product',
price:'2.95',
description: 'This is something you would need to buy!!'
}
})();
答案 2 :(得分:-2)
请注意ng-controller vs ng-repeat。
您希望将ng-controller属性设置为控制器名称,并使用不同的属性ng-repeat来重复数据。