2017-01-03 87 views
0

我是Web開發人員和學習AngularJS的初學者。我正在嘗試一些任務,並遇到一個問題,即函數(Angular controller)中定義的變量沒有在HTML中訪問,並且在瀏覽器中打開時什麼也沒有顯示。這個鏈接是:https://jsfiddle.net/2v41a6na/JavaScript變量不可用於HTML部分

代碼是:

<!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> 

Outpur上面的代碼爲:enter image description here

現在我無法理解爲什麼這一個工程,但不是第一個。他們都不使用$scope

+0

是否定義在$作用域varible? – Kenny

+0

像Halter說的那樣,$ scope是可以讓你通過HTML使用JavaScript變量的對象。您綁定到範圍的所有內容都將在視圖中提供。因此,並非所有變量都應該與範圍相關聯。例如:如果你有一些使用變量的邏輯。你不應該把它們綁在範圍上,而是用舊的方式使用它們。 –

回答

3

你並不需要聲明它$scope。第二個示例使用angular的controller as語法,其中變量和方法直接綁定到返回的控制器中。你有ng-controller="menuController as menuCtrl",所以菜單清單的值是menuCtrl.dishes

在你的第一個例子,你不使用controller as語法。你要麼需要使用例如ng-controller="dishDetailController as detailCtrl"這樣你就可以detailCtrl.dish訪問你的菜變量做,或者再爲其他人所說,你可以使用ng-controller="dishDetailController",然後在你的控制器$scope.dish = dish

編輯:點擊此處瞭解詳情:https://docs.angularjs.org/api/ng/directive/ngController#example

+0

好抓,是比其他更好的做法嗎?我一直使用範圍 – Halter

+0

檢查我的編輯,他們在那裏非常清楚地解釋它。我個人更喜歡''''''語法,因爲它使得它非常清楚你正在訪問哪個控制器的變量。例如,如果你有控制器在另一個控制器內部,使用'$ scope'方法,你只能訪問內部HTML中的內部控制器變量,但通過'controller as'你可以訪問其中的任何一個。 – Fissio

1

兩件事情

1)申報NG-應用在HTML作爲

<div class="container" ng-app="confusionApp"> 

2),並在控制器使用$的範圍,想

app.controller('dishDetailController', function($scope) { 

     $scope.dish={ 
         name:'Uthapizza', 
         image: 'images/uthapizza.png', 
         category: 'mains', 
         label:'Hot' 
     } 
}); 

小提琴https://jsfiddle.net/2v41a6na/1/

更新

它在HTML的工作,由於這條線

<div class="row row-content" ng-controller="menuController as menuCtrl"> 

即使你的代碼的工作只是你必須聲明你在HTML控制器一樣

<div class="row row-content" ng-controller="dishDetailController as dishes" > 

,代之以dishes.dish

所有的菜
<h2 class="media-heading">{{dishes.dish.name}} 
         <span class="label label-danger">{{dishes.dish.label}}</span> 

工作撥弄

https://jsfiddle.net/2v41a6na/3/

+0

太好了。你能看到EDIT1的問題,並告訴我這是如何工作的? – vvs14

+0

它工作,因爲ng-controller =「menuController as menuCtrl this – Kenny

+0

using menuCtrl他訪問變量存在於控制器內 – Kenny