角度JS不起作用

Angular JS not working

本文关键字:不起作用 JS 角度      更新时间:2023-09-26

我学习,这是我第一天的角度js! 虽然我已经了解了模型控制器视图在angular js中的工作原理,但 fowllowing 代码不显示变量,而是在没有ng-repeat工作的情况下给出正常的 {{}} HTML视图:

<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 src="lib/angular.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>

代码有什么问题?

只需替换

<html ng-app='myApp'>

<html ng-app>

它应该有效。

使用 ng-app='myApp',你可以告诉 angularjs 你有一个名为 myApp 的模块。但是您没有定义任何模块。

你应该定义你的myApp模块:

var app = angular.module('myApp', []);
app.controller('CartController', ['$scope', 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);
    }
}]);

演示

基本上你没有在控制器中定义module

<script>
 angular.module('myApp', []);  // add this line
        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>

您在普伦克的演示