Ribeiro
Ribeiro

Reputation: 374

Pass Variable from jQuery to Angular

Here's my select 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>

I have the following jQuery code to get me the id from any giving option in a select.

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

And then this Angular Code to fill out a table with 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;
    });
});

Here's the table that is populated with the Angular Code:

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

The problem is that i can't seem to pass the id attribute that i get from jQuery to the $http.get, however if i declare id inside the angular code it works fine. The idea is that every time someone changes the option for the restaurant in the select it updates the table with the new menu data. Thanks ! Any Suggestions to make it work?

Upvotes: 1

Views: 1522

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16069

You can do that with your existing code like this:

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;
        });
    });
});

However, it is not the goal of angular to use jQuery for getting a DOM element's value. You should think about using ng-model in <select/>. This will return you the value of the selected <option/> into the $scope variable. See this example:

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;
        });
    };
});

Upvotes: 3

Related Questions