如何添加angularJs表达式{{}}作为函数参数

时间:2016-07-05 10:21:34

标签: angularjs

我如何通过角度表达"小胡子"像这样{{dish.id}}到

<button ng-click="singleDish()">

发表评论

这是按钮的控制器代码..

$scope.dishId = '0';
$scope.singleDish = function(id){
    $scope.dishId == id;
};
$scope.dish = menuFactory.getDish($scope.dishId);

所以当点击按钮时

i tried (dish.id) ----- didnt work (doesnt change the scope variable dishId)
    ('{{dish.id}}') didnt work (doesnt change the scope variable dishId)
    ({{dish.id}}) caused an error.

如果有我的整个代码..

menu.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>Ristaurant Menu</title>
                  <!-- Bootstrap -->

            <!-- build:css styles/main.css -->
                <!-- 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">
            <!-- endbuild -->
                <!-- 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">
                        <div class="col-xs-12"> 
                            <button class="btn btn-xs btn-primary pull-right" ng-click="toggleDetails()">{{showDetails? 'Hide Details' : 'Show Details'}}</button>
                            <span class="pull-right">&nbsp; &nbsp;</span>
                            <button class="btn btn-xs btn-primary pull-right" ng-click="toggleComment()">{{showComment? 'Hide Comments' : 'Show Comments'}}</button>
                          <ul class="nav nav-tabs" role="tablist">
                              <li role="presentation"
                               ng-class="{active:isSelected(1)}">
                                  <a ng-click="select(1)"
                                   aria-controls="all menu"
                                   role="tab">The Menu</a>
                              </li>
                              <li role="presentation"
                               ng-class="{active:isSelected(2)}">
                                  <a ng-click="select(2)"
                                   aria-controls="appetizers"
                                   role="tab">Appetizers</a>
                              </li>
                              <li role="presentation"
                               ng-class="{active:isSelected(3)}">
                                  <a ng-click="select(3)"
                                   aria-controls="mains"
                                   role="tab">Mains</a>
                              </li>
                              <li role="presentation"
                               ng-class="{active:isSelected(4)}">
                                  <a  ng-click="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 dishes |filter: filtText">
                                    <div class="row">
                                        <div class="col-xs-2">
                                              <div class="media-left media-middle">
                                                  <a href="#">
                                                  <img class="media-object img-thumbnail"
                                                   ng-src={{dish.image}} alt="Uthappizza">
                                                  </a>
                                              </div>
                                        </div>

                                    <!-- <div class="media-body"> -->
                                        <!-- <div class="row"> -->
                                            <div class="col-xs-10">
                                                <h2 class="media-heading">{{dish.name}}
                                                <span class="label label-danger">{{dish.label}}</span>
                                                <span class="badge">{{dish.price | currency}}</span></h2>
                                                <p ng-show="showDetails">{{dish.description}}</p>
                                            </div>
                                            </div>
                                        <!-- </div> -->
                                        <div class="row">
                                            <div class="col-xs-10 col-xs-offset-1">
                                                <div ng-show="showComment">
                                                    <blockquote class="col-sm-12"ng-repeat = "comment in dish.comment | orderBy : sort">
                                                        <h4>{{comment.comment}}</h4>
                                                        <h5>{{comment.rating}} Stars.</h5>
                                                        <footer>
                                                            <cite title="Source Title">{{comment.author}} @ {{comment.date | date: 'dd MMMM,yyyy'}}</cite>
                                                        </footer>
                                                    </blockquote>
                                                    <p class="leaD"> ID: {{dish.id}} </p>
                                                    <div  ng-controller="DishDetailController">
                                                        <button class="btn btn-default" ng-click="singleDish({{dish.id}})">
                                                            <a href="dishDetail.html"><h4> Leave your Comment </h4></a>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>

                                        </div>
                                    <!-- </div> -->

                                </li>
                            </ul>
                          </div>
                        </div>
                    </div>
                </div>

                <!-- build:js scripts/main.js -->
              <script src="../bower_components/angular/angular.min.js"></script>
              <script src="scripts/app.js"></script>
              <script src="scripts/controllers.js"></script>
              <script src="scripts/services.js"></script>
            <!-- endbuild -->
            </body>

            </html>

app.js

'use strict';
  angular.module('confusionApp',[]);

Controller.js

                'use strict';
            angular.module('confusionApp')
            .controller('MenuController',['$scope','menuFactory', function($scope, menuFactory) {
              $scope.tab = 1;
              $scope.filtText = '';
              $scope.showDetails = false;

              $scope.dishes = menuFactory.getDishes();

              $scope.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 = "";
                }
              };

              $scope.isSelected = function (checkTab) {
                return (this.tab === checkTab);
              };

              $scope.toggleDetails = function(){
               // !$scope.showDetails? $scope.showDetails = true : $scope.showDetails = false;  ==> Valid solution.
                  $scope.showDetails = !$scope.showDetails;
              };
              $scope.toggleComment = function(){
                  $scope.showComment = !$scope.showComment;
              };
            }])
            .controller('DishDetailController',['$scope','menuFactory',function($scope, menuFactory) {
                $scope.dishId = '0';
                $scope.singleDish = function(id){
                    $scope.dishId == id;
                };
                $scope.dish = menuFactory.getDish($scope.dishId);
                $scope.sort = '';

                $scope.comment = {
                    name: '',
                    stars: '',
                    comment: ''
                };
                $scope.submitComments = function(){
                    $scope.dish.comment.push({
                        rating: $scope.comment.stars,
                        comment: $scope.comment.comment,
                        author: $scope.comment.name,
                        date:Date.now()
                    });
                    $scope.comment = {
                    name: '',
                    stars: '',
                    comment: ''
                };
                    $scope.commentForm.$setPristine();
                };
             }])
            .controller('FeedbackController',['$scope', function ($scope) {

               $scope.feedback = {
                    myChannel:"",
                    firstName: '',
                    lastName: '',
                    agree: false,
                    email: ''
                  };
                $scope.channels = [
                  {
                    value:"tel",
                    label:"Tel."
                  }, {
                    value:"Email",
                    label:"Email"
                  }
                ];
                  $scope.invalidChannelSelection = false;
                // when submit //
                $scope.sendFeedback = function() {
                  console.log($scope.feedback);
                  if ($scope.feedback.agree && ($scope.feedback.myChannel === "")) {
                        $scope.invalidChannelSelection = true;
                        console.log('incorrect');
                  }
                  else {
                        $scope.invalidChannelSelection = false;
                        $scope.feedback = {myChannel:"", firstName:"", lastName:"",
                                           agree:false, email:"" };
                        $scope.feedback.myChannel="";

                        $scope.feedbackForm.$setPristine();
                        console.log($scope.feedback);
                  }
                };
            }])
            /* .controller('CommentsController',['$scope', function($scope){

            }]) */;

services.js

angular.module('confusionApp').service('menuFactory', function(){

var dishes = [
{
  id: 0,
  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:  [
            {
                   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"
           }
        ]
},
{
  id: 1,
  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: [
            {
                   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"
           }
        ]
},

{
  id: 2,
  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: [
            {
                   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"
           }
        ]
},

{
  id: 3,
  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: [
            {
                   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.getDishes = function(){

    return dishes;
};

this.getDish = function(index){

    return dishes[index];
};

});

提前谢谢。

2 个答案:

答案 0 :(得分:1)

在您的功能中进行比较而不是分配(==而不是=),这应该有效:

<button ng-click="singleDish(dish.id)">

$scope.singleDish = function(id){
    $scope.dishId = id; // notice: 1 `=` for assignment
};

有关比较器/分配器here的更多信息。

  

通过使用=,您可以为某个值指定值。

x = 1 //x now equals 1 
x = 2 //x now equals 2 
  

通过使用==,您可以检查某些内容是否与其他内容相同。这不严格

x == 1 //is x equal to 1? (False) 
x == 2 //is x equal to 2? (True)
true == 1 //does the boolean value of true equal 1? (True) 
  

通过使用===,您可以检查某些内容是否与其他内容相同。这也很严格。

x === 1 //is x equal to 1? (False) 
x === 2 //is x equal to 2? (True)
true === 1 //does the boolean value of true equal 1? (False) 
  

如果不清楚那么严格的是,它不仅检查两个值的相等性,还比较两个值的类型   价值也是。使用==将尝试转换表达式的一侧   与另一个是同一类型。例如,布尔和整数。   true的布尔值是1,因此1等于1?是的,没错。   但是,当使用strict时,它在尝试之前不会尝试转换   比较,它检查true是否等于1,这不是它们   是两种不同的数据类型,并返回false。

答案 1 :(得分:1)

只需将变量直接传递给这样的方法,然后使用&#39; =&#39;运营商。 ==和===用于比较。在此处阅读更多内容:Which equals operator (== vs ===) should be used in JavaScript comparisons?

<button ng-click="singleDish(dish.id)">

<强>控制器

 $scope.singleDish = function(id){
  console.log('Here is the id ' + id);
 };