簡體   English   中英

將變量從jQuery傳遞給Angular

[英]Pass Variable from jQuery to Angular

這是我選擇的HTML

<label for="SelectMenu">Select the Menu</label><br>
<select id="SelectMenu" name="SelectMenu" ng-init="">
  <?php foreach ($list as $lista): ?>
  <option value="<?php echo $lista->MENU_ID; ?>"><?php echo $lista->MENU_NAME; ?></option>
  <?php endforeach;  ?>
</select>

我有以下jQuery代碼來獲取select中任何給定選項的id。

$("#SelectMenu").change(function() {
var id = $(this).find("option:selected").val();
console.log(id); });

然后這個Angular Code用ng-repeat填寫表格。

var app = angular.module('myApp', []);
app.controller('dishesCtrl', function($scope, $http) {
// var id = 1;
$http.get('http://192.168.1.162/dw/rest/menu_info/' + id)
    .then(function(response) {
        $scope.info = response.data;
    });
});

這是使用Angular代碼填充的表:

<table class="table table-striped table-hover" ng-controller="dishesCtrl">
    <th> Dish </th>
    <th> Type</th>
    <th> Price (€)</th>
    <tr ng-repeat="x in info">
        <td> {{x.DISH_NAME}} </td>
        <td> {{x.DISH_TYPE}} </td>
        <td> {{x.PRICE_VALUE}} </td>
    </tr>
</table>

問題是我似乎無法將從jQuery獲取的id屬性傳遞給$ http.get,但是如果我在角度代碼中聲明id它可以正常工作。 這個想法是,每當有人在選擇中更改餐廳的選項時,它會使用新的菜單數據更新表格。 謝謝 ! 有什么建議讓它起作用嗎?

您可以使用現有代碼執行此操作,如下所示:

var app = angular.module('myApp', []);
app.controller('dishesCtrl', function($scope, $http) {
    $("#SelectMenu").change(function() {
        var id = $(this).find("option:selected").val();
        $http.get('http://192.168.1.162/dw/rest/menu_info/' + id)
          .then(function(response) {
              $scope.info = response.data;
        });
    });
});

但是,使用jQuery獲取DOM元素值不是angular的目標。 您應該考慮在<select/>使用ng-model 這會將所選<option/>的值返回到$ scope變量中。 看這個例子:

HTML

<select id="SelectMenu" name="SelectMenu" ng-init="" ng-model="SelectMenu.id" ng-change="updateSelectMenu()">
    <?php foreach ($list as $lista): ?>
      <option value="<?php echo $lista->MENU_ID; ?>"><?php echo $lista->MENU_NAME; ?></option>
    <?php endforeach; ?>
</select>

JavaScript的

app.controller('dishesCtrl', function($scope, $http) {
    $scope.SelectMenu = {};

    $scope.updateSelectMenu = function() {
        $http.get('http://192.168.1.162/dw/rest/menu_info/' + $scope.SelectMenu.id)
          .then(function(response) {
              $scope.info = response.data;
        });
    };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM