rtn
rtn

Reputation: 2034

Angularjs append values within angular.forEach

Need a bit of help with angular and check boxes and how would put together one variable with all the checked values in. Here's what I have got so far but can't seem to figure out a good way on concatenating all the values which are checked so they can be shipped of to a REStful $resource. How would I get some variable or $scope item with all the checked values in it in the following format. e.g.:

types = Permanent,Contract,Any,Fixed Term 

sample data of checkboxes ($scope.newJobSearch.type):

{
  "Permanent": "Permanent",
  "Contract": "Contract",
  "Permanent or Contract": false,
  "Any": "Any",
  "Fixed Term": "Fixed Term"
}

<label class="checkbox-inline" for="{{jobType}}" ng-repeat="jobType in jobTypes ">
  <input type="checkbox" id="{{jobType}}" value="{{jobType}}" ng-model="newJobSearch.type[jobType]" ng-true-value="{{jobType}}" ng-click="jobTypesCheck()"> {{jobType}}
</label>

$scope.newJobSearch = {};

function searchJobs(newJobSearch) {                  
  angular.forEach(newJobSearch.type, function (value) {
    if (value != false) {
      $scope.queryTypes.push(value); //Dose not seem to work
      //Some var in here which contains all the string values e.g:
      //Permanent,Contract,Fixed Term
    }
  });
}

Upvotes: 0

Views: 1643

Answers (2)

enguerranws
enguerranws

Reputation: 8233

I don't understand your code at all. Anyway, I think you're looking for something like :

$scope.jobTypes =  ['Permanent','Contract','Any','Fixed Term'];
$scope.newJobSearch;
$scope.newJobSearch.type = [];
$scope.newJobSearch.type.checked = $filter('filter')($scope.newJobSearch.type, {checked: true});

Then :

<label class="checkbox-inline" for="{{jobType}}" ng-repeat="jobType in jobTypes ">
        <input type="checkbox" id="{{jobType}}" value="{{jobType}}" ng-model="newJobSearch.type[$index]" > {{jobType}}
</label>

You don't need a function to bind data to the model, as Angular will do it by itself.

Upvotes: 0

meriadec
meriadec

Reputation: 2983

See this jsFiddle

You can use a combination of ng-repeat and ng-change for updating your result set :

controller :

$scope.result = {};

$scope.items = [
  { name: "Permanent", checked: false },
  { name: "Contract", checked: false },
  { name: "Permanent or Contract", checked: false },
  { name: "Any", checked: false },
  { name: "Fixed", checked: false }
];

$scope.updateResult = function () {
  $scope.items.forEach(function (item) {
    $scope.result[item.name] = item.checked ? item.name : false;
  });
};

$scope.updateResult();

html :

<div ng-repeat="item in items">
  <input ng-model="item.checked"
         ng-change="updateResult()"
         type="checkbox">
  {{ item.name }}
</div>

Upvotes: 1

Related Questions