Reputation: 1335
I have been struggling with this for ages and I just can't seem to find a solution, for something I feel is relatively simple.
I want the user to click a button, then that button will take all the selected items in a select box and put them in an object.
Here is the JQuery code that can accomplish this for me -
$("#addUserGroup").click(function () {
var selectedValues = [];
$("#UserGroups :selected").each(function () {
selectedValues.push($(this).val());
});
alert(selectedValues);
});
I want to accomplish the same thing but to have the object accessible within my angular controller. If anyone could point me in the right direction it would be greatly appreciated.
EDIT:
The answer below solves the issue, but here is my slight modification to deal with selecting multiple items if you have a select that allows for that.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.values = [];
$scope.selectedValue = "foo";
$scope.addValue = function () {
$scope.values.push($scope.selectedValue);
console.log($scope.values);
for (i = 0; i < $scope.values.length; i++) {
console.log($scope.values[i]);
}
//Do whatever with option list values
//Reset values array so it is empty for next click
$scope.values = [];
}
});
Upvotes: 1
Views: 267
Reputation: 816
I had a go at this problem and basically ended up using ng-model for the and ng-click for the .
JS
app.controller('MainCtrl', function($scope) {
$scope.values = [];
$scope.selectedValue = "foo";
$scope.addValue = function () {
$scope.values.push($scope.selectedValue);
console.log($scope.values);
}
});
HTML
<body ng-controller="MainCtrl">
<select ng-model="selectedValue">
<option>foo</option>
<option>bar</option>
<option>foobar</option>
</select>
<button ng-click="addValue()">Add</button>
Hope this helps.
http://plnkr.co/edit/afOIDxki62Tuz9csNz4O?p=info
Upvotes: 2