javascript - Angular 不是双向绑定(bind)

标签 javascript angularjs angularjs-ng-repeat

试图自学 AngularJS,但我一直在学习如何构建一个简单的购物车的教程。我终生无法弄清楚为什么我的 {{}} Angular 标签没有在 View 中显示数据,而是显示文字字符串(即 {{item.price | currency}})有什么见解吗?我担心代码没有引用 Angular 库,但来源是正确的 - 该库保存为 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>`

最佳答案

当您将值设置为 ng-app 时(比如 ng-app="MyApp" ),Angular.JS 会期望你有类似 var myModule = angular.module("MyApp", []) 的东西.

它只会在其中寻找 Controller ,使用 myModule.controller()方法(或者可以直接在模块调用之后)。全局函数将不起作用。

所以,您有 2 个选择:

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

  2. 创建模块:

    angular.module("MyApp", []).controller("CartController", function($scope) {
        /// ...
    });
    

请注意,如果您使用的是 Angular.JS 1.3,则必须使用方法 2,因为在该版本中删除了全局作用域函数方法。

关于javascript - Angular 不是双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717081/

相关文章:

javascript - canplaythrough 事件和 HTM5 音频 : can anyone remove this event?

angularjs - Angular : How to load images through XHR request in ng-repeat loop

javascript - 将 md-fab-toolbar 与 ng-repeat 结合使用

javascript - 数组过滤器为空时返回全部

javascript - 如何在javascript中的回调函数之后获取for循环中递增的值?

javascript - 通过特定键访问对象

javascript - 一旦文本从一个 UL 移动到另一个 UL,就禁用文本

javascript - Angular ng-repeat 重复 tr 与多个 td

javascript - 根据选择选项值禁用输入字段 Angularjs

javascript - AngularJS : Display a property value of multiple objects in an input text field, 逗号分隔