Angular ng-controller问题

时间:2014-08-25 12:48:27

标签: angularjs

正在进行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}}

请帮我解决我的错误。

3 个答案:

答案 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来重复数据。