javascript 变量不可用于 HTML 部分

标签 javascript html angularjs

我是 Web 开发初学者,正在学习 AngularJS。我正在尝试一些分配,并遇到了函数(Angular Controller )中定义的变量无法在 HTML 中访问并且在浏览器中打开时不显示任何内容的问题。链接为:https://jsfiddle.net/2v41a6na/

代码是:

<!DOCTYPE html>
<html lang="en" ng-app="confusionApp">

<head>
     <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head
         content must come *after* these tags -->
    <title>Ristorante Con Fusion: Menu</title>
        <!-- Bootstrap -->
    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>

    <div class="container">
        <div class="row row-content" ng-controller="dishDetailController" >
            <div class="col-xs-12">
                <div class="media">
                    <div class="media-left media-middle">
                        <a href="#">
                            <img class="media-object img-thumbnail" ng-src={{dish.image}} alt="Uthappizza">
                        </a>
                    </div>
                    <div class="media-body">
                        <h2 class="media-heading">{{dish.name}}
                            <span class="label label-danger">{{dish.label}}</span>
                            <span class="badge">{{dish.price | currency}}</span>
                        </h2>
                        <p>{{dish.description}}</p>
                    </div>
                </div>
                <!--<p>Put the dish details here</p>-->
            </div>
            <div class="col-xs-9 col-xs-offset-1">
                <p>Put the comments here</p>
            </div>
        </div>

    </div>

    <script src="../bower_components/angular/angular.min.js"></script>
    <script>

        var app = angular.module('confusionApp',[]);
        
        app.controller('dishDetailController', function() {

            var dish={
                          name:'Uthapizza',
                          image: 'images/uthapizza.png',
                          category: 'mains', 
                          label:'Hot',
                          price:'4.99',
                          description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                           comments: [
                               {
                                   rating:5,
                                   comment:"Imagine all the eatables, living in conFusion!",
                                   author:"John Lemon",
                                   date:"2012-10-16T17:57:28.556094Z"
                               },
                               {
                                   rating:4,
                                   comment:"Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                                   author:"Paul McVites",
                                   date:"2014-09-05T17:57:28.556094Z"
                               },
                               {
                                   rating:3,
                                   comment:"Eat it, just eat it!",
                                   author:"Michael Jaikishan",
                                   date:"2015-02-13T17:57:28.556094Z"
                               },
                               {
                                   rating:4,
                                   comment:"Ultimate, Reaching for the stars!",
                                   author:"Ringo Starry",
                                   date:"2013-12-02T17:57:28.556094Z"
                               },
                               {
                                   rating:2,
                                   comment:"It's your birthday, we're gonna party!",
                                   author:"25 Cent",
                                   date:"2011-12-02T17:57:28.556094Z"
                               }
                               
                           ]
                    };
            
            this.dish = dish;
            
        });

    </script>

</body>

</html>

预期的设计应该像 enter image description here

编辑1:我没有使用上面的$scope。 我有类似的代码,可以完美运行,但设计不同。代码是

<!DOCTYPE html>
<html lang="en" ng-app="confusionApp">

<head>
     <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head
         content must come *after* these tags -->
    <title>Ristorante Con Fusion: Menu</title>
        <!-- Bootstrap -->
    <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-social.css" rel="stylesheet">
    <link href="styles/mystyles.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>

    <div class="container">
        <div class="row row-content" ng-controller="menuController as menuCtrl">
            <div class="col-xs-12">
                <ul class="nav nav-tabs" role="tablist">
                    <li role="presentation" ng-class="{active:menuCtrl.isSelected(1)}"><a ng-click="menuCtrl.select(1)" aria-controls="all menu" role="tab"> The Menu</a> </li>
                    <li role="presentation" ng-class="{active:menuCtrl.isSelected(2)}"><a ng-click="menuCtrl.select(2)" aria-controls="appetizers" role="tab"> Appetizers</a> </li>
                    <li role="presentation" ng-class="{active:menuCtrl.isSelected(3)}"><a ng-click="menuCtrl.select(3)" aria-controls="mains" role="tab"> Mains</a> </li>
                    <li role="presentation" ng-class="{active:menuCtrl.isSelected(4)}"><a ng-click="menuCtrl.select(4)" aria-controls="desserts" role="tab"> Desserts</a> </li>
                </ul>
                <div class="tab-content">
                    <ul class="media-list tab-pane fade in active">
                        <li class="media" ng-repeat="dish in menuCtrl.dishes | filter:menuCtrl.filtText">
                            <div class="media-left media-middle">
                                <a href="#">
                                    <img class="media-object img-thumbnail" ng-src={{dish.image}} alt="Uthappizza">
                                </a>
                            </div>
                            <div class="media-body">
                                <h2 class="media-heading">{{dish.name}}
                                    <span class="label label-danger">{{dish.label}}</span>
                                    <span class="badge">{{dish.price | currency}}</span>
                                </h2>
                                <p>{{dish.description}}</p>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <script src="../bower_components/angular/angular.min.js"></script>
    <script>
        var app = angular.module('confusionApp',[]);
        app.controller('menuController', function(){
             this.tab =1;
             var dishes=[
                         {
                           name:'Uthapizza',
                           image: 'images/uthapizza.png',
                           category: 'mains',
                           label:'Hot',
                           price:'4.99',
                           description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
                           comment: ''
                        },
                        {
                           name:'Zucchipakoda',
                           image: 'images/zucchipakoda.png',
                           category: 'appetizer',
                           label:'',
                           price:'1.99',
                           description:'Deep fried Zucchini coated with mildly spiced Chickpea flour batter accompanied with a sweet-tangy tamarind sauce',
                           comment: ''
                        },
                        {
                           name:'Vadonut',
                           image: 'images/vadonut.png',
                           category: 'appetizer',
                           label:'New',
                           price:'1.99',
                           description:'A quintessential ConFusion experience, is it a vada or is it a donut?',
                           comment: ''
                        },
                        {
                           name:'ElaiCheese Cake',
                           image: 'images/elaicheesecake.png',
                           category: 'dessert',
                           label:'',
                           price:'2.99',
                           description:'A delectable, semi-sweet New York Style Cheese Cake, with Graham cracker crust and spiced with Indian cardamoms',
                           comment: ''
                        }
                        ];
            this.dishes= dishes;
            this.filtText= '';
            
            this.select = function(setTab){
                this.tab = setTab;
                if(setTab==2)
                    this.filtText= 'appetizer';
                else if (setTab==3)
                    this.filtText= 'mains';
                else if (setTab ==4)
                    this.filtText = 'dessert';
                else
                    this.filtText = '';
            }
            this.isSelected = function(checkTab){
                return (this.tab == checkTab);
            }
        })
    </script>
</body>

</html>

上述代码的输出为:enter image description here

现在我无法理解为什么这个有效但第一个无效。它们都不使用 $scope

最佳答案

您不需要在$scope中声明它。第二个示例使用 Angular 的 controller as 语法,其中变量和方法直接绑定(bind)到返回的 Controller 中。您有 ng-controller="menuController as menuCtrl",因此菜肴列表就是 menuCtrl.dishes 的值。

在第一个示例中,您没有使用controller as 语法。您要么需要使用 ng-controller="dishDetailController asDetailCtrl" 来完成此操作,以便您可以使用 detailCtrl.dish 访问您的菜肴变量,或者像其他人一样也就是说,您可以使用 ng-controller="dishDetailController" ,然后在 Controller 中使用 $scope.dish = duck

编辑:更多信息在这里:https://docs.angularjs.org/api/ng/directive/ngController#example

关于javascript 变量不可用于 HTML 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445135/

相关文章:

Javascript 或 jquery 版本的 sencha touch 嵌套列表?

javascript - 对于 20 多个元素,哪个 jQuery 操作更快?

javascript - 保持风格的按钮

html - 过渡缓入缓出;不管用

html - 过渡效果创建错误

javascript - 重置选择器未正确重置表数据

javascript - 无法使用 Internet Explorer 11 登录 Firebase

javascript - 如何将输入和 slider 放在一起

javascript - 如何将页面添加到现有的 AngularJS 应用程序?

AngularJS : Chrome hidden fields value don't update after page return