Reputation: 5485
I am new to angularjs, actually from jQuery background, I have created a fiddle which demonstrates the selected options in the array. But in between I have used the jQuery $.each function (may be have to use angular.forEach, but did not achieve the result),
1.Please correct me the functionality completely by using only angular functions,
2. And also please suggest me feasible/standard way of doing this feature. As this number of checkbox may increase or decrease along with the options in the select box.
<div ng-app="checkbox" ng-controller="chkController">
Check me to select: <br/>
<input type="checkbox" ng-model="selected1" ng-click="getSelectedIds()" />Hello 1<br/>
<input type="checkbox" ng-model="selected2" ng-click="getSelectedIds()" />Hello 2<br/>
<input type="checkbox" ng-model="selected3" ng-click="getSelectedIds()" />Hello 3<br/>
<input type="checkbox" ng-model="selected4" ng-click="getSelectedIds()" />Hello 4<br/>
<input type="checkbox" ng-model="selected5" ng-click="getSelectedIds()" />Hello 5<br/>
<select id="selectBox" multiple="multiple" style="width:200px;" >
<option id="greet1" ng-selected="selected1">Hello 1!</option>
<option id="greet2" ng-selected="selected2">Hello 2!</option>
<option id="greet3" ng-selected="selected3">Hello 3!</option>
<option id="greet4" ng-selected="selected4">Hello 4!</option>
<option id="greet5" ng-selected="selected5">Hello 5!</option>
</select>
<input type="button" value="Show Selected" ng-click="showValues();" />
</div>
And In My controller
var checkbox = angular.module('checkbox', []);
checkbox.controller('chkController', function($scope){
$scope.myArr = [];
$scope.getSelectedIds = function(){
$("select option").each(function(i, j){
if($(j).is(':selected') && ($scope.myArr.indexOf($(j).attr("id")) == -1)){
$scope.myArr.push($(j).attr("id"));
}
});
};
$scope.showValues = function(){
console.log($scope.myArr);
}
});
Upvotes: 0
Views: 53
Reputation: 8465
I've took your jsfiddle and updated it to be more angular way
as you can see I've implemented 2 ng-repeat
<label ng-repeat="chk in dataForCheckboxes" style="display: block"><input type="checkbox" ng-model="chk.selected"/>{{chk.label}}</label>
<select id="selectBox" multiple="multiple" style="width:200px;height: 300px;" ng-model="selectedChk">
<option value="{{chk.label}}" ng-repeat="chk in dataForCheckboxes" ng-selected="chk.selected">{{chk.label}}</option>
it's because in MVC the View should be driven by Controller
Information on angularJS $filter
Cheers
Upvotes: 1