试图自学 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 个选择:
替换
<html ng-app="MyApp">
与<html ng-app>
创建模块:
angular.module("MyApp", []).controller("CartController", function($scope) { /// ... });
请注意,如果您使用的是 Angular.JS 1.3,则必须使用方法 2,因为在该版本中删除了全局作用域函数方法。
关于javascript - Angular 不是双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717081/