ng-controller不将数据呈现给浏览器

时间:2016-09-22 05:42:15

标签: javascript angularjs angularjs-directive

我是Angular JS的新手,我在ng-controller中面临一些问题,即没有向浏览器屏幕发送值。我使用角1.5.8。如何让这段代码显示值.Attached也是我的输出 enter image description here 这是我的代码: 的script.js

(function () {
var gem = {
    name: "Dodecahedron",
    price: 2.95,
    description: "great stone"
};
var app = angular.module('store', []);
app.controller('StoreController', function () {
    this.product = gem;
});
})();

html文件

<!DOCTYPE html>
<html data-ng-app="store">
<head>
    <script type="text/javascript" src="angular.js"></script>
    <script type="text/javascript" src="script.js" ></script>
    <link rel="stylesheet" type="text/css"       href="bootstrap/bootstrap/css/bootstrap.min.css">
    <meta charset="UTF-8">
    <title>Angular Demo</title>
</head>
<body >
{{"Hello" + "Angular"}}
<br />
Here is Where our gem information will be displayed through the controller.

<div ng-controller="StoreController">
    {{"Hello" + "Angular"}}
    <h1>Product name : {{StoreController.product.name}}</h1>
    <h2>Produce Price : {{StoreController.product.price}}</h2>
    <p>Product Description : {{StoreController.product.description}}</p>
</div>

</body>
</html>

4 个答案:

答案 0 :(得分:1)

您应该使用$ scope variable

app.controller('StoreController', function ($scope) {
    $scope.product = gem;
});

DEMO

否则您可以使用Controller作为语法。

答案 1 :(得分:1)

您缺少“StoreController作为StoreController”

<div ng-controller="StoreController as StoreController">
    {{"Hello" + "Angular"}}
    <h1>Product name : {{StoreController.product.name}}</h1>
    <h2>Produce Price : {{StoreController.product.price}}</h2>
    <p>Product Description : {{StoreController.product.description}}</p>
</div>

工作人员here

答案 2 :(得分:1)

您可以在控制器

中使用$ scope变量
app.controller('StoreController', function ($scope) {
    $scope.product = gem;
});

在html中你可以像这样直接访问$ scope变量

<div ng-controller="StoreController">
    {{"Hello" + "Angular"}}
    <h1>Product name : {{product.name}}</h1>
    <h2>Produce Price : {{product.price}}</h2>
    <p>Product Description : {{product.description}}</p>
</div>

答案 3 :(得分:0)

如果您不想使用$scope,可以使用controller as systax。

<div ng-controller="StoreController as ctrl">
    {{"Hello" + "Angular"}}
    <h1>Product name : {{ctrl.product.name}}</h1>
    <h2>Produce Price : {{ctrl.product.price}}</h2>
    <p>Product Description : {{product.description}}</p>
</div>