简体   繁体   中英

Converting jQuery to Angular - Click Button change options in Dropdown Menu

I wanted to add some AngularJS functionalities to an existing site in which I am using jQuery. I have the following problem:

In jQuery, when I click a button, the dropdown item changes. Please see jsfiddle below:

 $('#cameratagete').click(function() { $('#rooms option[value="Camera Tagete"]').attr('selected', true); }); $('#cameraoleandro').click(function() { $('#rooms option[value="Camera Oleandro"]').attr('selected', true); }); $('#cameragelsomino').click(function() { $('#rooms option[value="Camera Gelsomino"]').attr('selected', true); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="cameratagete" href="#">Item 1</a> <a id="cameraoleandro" href="#">Item 2</a> <a id="cameragelsomino" href="#">Item 3</a> <form> <select id="rooms"> <option value="1">I dont know</option> <option value="Camera Tagete">Tagete</option> <option value="Camera Oleandro">Oleandro</option> <option value="Camera Gelsomino">Gelsomino</option> </select> </form> 

http://jsfiddle.net/almostpitt/0b7fybjr/

When I use this in a form in Angular, the item is still chosen on the form and you can see it visually on the page, however, it is not read by the form in the sense that when you submit the form, the option is not sent.

However, if you select that option directly on the dropdown and submit the form, the option is submitted as well.

My question is, can I convert this piece of jQuery into AngularJS? I'm hoping that this would allow the form to read the selected item.

Thanks!

Note: I am using Angular 1.5.5.

Prettty easy to achieve this with AngularJS like in this runnable fiddle .

View

<div ng-controller="MyCtrl">

  <a id="cameratagete" ng-click="selected = '1'">Select: Item 1</a><br/>
  <a id="cameratagete" ng-click="selected = 'Camera Tagete'">>Select: Item 2</a><br/>
  <a id="cameratagete" ng-click="selected = 'Camera Oleandro'">>Select: Item 3</a><br/>

  <form method="post" action="./test">
    <select id="rooms" ng-model="selected" name="someOption">
      <option value="1">I dont know</option>
      <option value="Camera Tagete">Tagete</option>
      <option value="Camera Oleandro">Oleandro</option>
      <option value="Camera Gelsomino">Gelsomino</option>
    </select>
    <br />
    <button type="submit">
      Send
    </button>
  </form>
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.selected = '1';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM