角度不是双向绑定

时间:2014-09-08 03:29:07

标签: javascript angularjs angularjs-ng-repeat

尝试自学AngularJS,并坚持试图建立一个简单的购物车的教程。我不能为我的生活弄清楚为什么我的{{}}角标签没有在视图中显示数据,而是显示文字字符串(即{{item.price | currency}})任何见解?我担心代码不引用角度库,但源是正确的 - 库保存为angular.min.js。

请帮忙!

`

<html ng-app='myApp'>
<head>
    <title>Your Shopping Cart </title>
</head>
<body ng-controller='CartController'>
    <h1> Your order</h1>
    <div ng-repeat='item in items'>
        <span>{{item.title}}</span>
        <input ng-model='item.quantity'>
        <span>{{item.price | currency}}</span>
        <span>{{item.price * item.quantity | currency}}</span>
        <button ng-click="remove($index)">Remove</button>
    </div>
    <script type="text/javascript" src="angular.min.js"></script>
    <script>
        function CartController($scope){
            $scope.items = [
                {title: 'Paint pots', quantity: 8, price: 3.95},
                {title: 'Polka dots', quantity: 17, price: 12.95},
                {title: 'Pebbles', quantity: 5, price: 6.95}
            ];

            $scope.remove = function(index){
                $scope.items.splice(index, 1);
            }
        }
    </script>
</body>
</html>`

3 个答案:

答案 0 :(得分:2)

当您将值设置为ng-app(例如ng-app="MyApp")时,Angular.JS会希望您拥有类似var myModule = angular.module("MyApp", [])的内容。

它将使用myModule.controller()方法(或者可以直接在模块调用之后)查找内部的控制器。全局功能不起作用。

所以,你有两个选择:

  1. <html ng-app="MyApp">替换为<html ng-app>

  2. 创建模块:

    angular.module("MyApp", []).controller("CartController", function($scope) {
        /// ...
    });
    
  3. 请注意,如果您使用 Angular.JS 1.3 ,则必须使用方法2,因为在该版本中删除了全局范围函数方式。

答案 1 :(得分:1)

这是因为CartController只是一个简单的函数。您必须将其添加为myApp模块

下的控制器
angular.module("maApp", []).
controller("CartController", function ($scope) {
        $scope.items = [
            {title: 'Paint pots', quantity: 8, price: 3.95},
            {title: 'Polka dots', quantity: 17, price: 12.95},
            {title: 'Pebbles', quantity: 5, price: 6.95}
        ];

        $scope.remove = function(index){
            $scope.items.splice(index, 1);
        }
})

答案 2 :(得分:1)

我认为你正在尝试Angularjs Book中的这个例子,他们明确提到我们没有为每个例子初始化应用程序,你需要初始化你的应用程序。或者只是忽略app,从控制器开始编码。当你提到ng-app =&#34; sample&#34;你需要引导它,以便使用控制器指令和你使用的一切。如果您不想初始化,那么您可以简单地离开ng-app =&#34;&#34;空白。这是工作示例[小提琴] [1]

 [1]: http://jsfiddle.net/kaLropns/
相关问题