Call a function with a variable name depending on the checkboxes clicked

111 views Asked by At

What I am trying to do is to make a search function. I want to have multiple options by using checkboxes and depending on the value of each checkbox to call a function in the controller. In details what I have done until now is a dropdown menu:

<input type="text" placeholder="Search Keyword..." ng-model="searchKeyword">
<select ng-model="selectedProperty">
    <option value="usersUsername">Users: Username</option>
    <option value="accountsName">Accounts: Name</option>
</select>
<button type="submit" ng-click="search()">Search</button>

and in the controller I am checking which property has been selected and I am calling the corresponding function

$scope.search = function () {
  switch ($scope.selectedProperty) {
    case 'usersUsername':
        searchByUsersUsername($scope.searchKeyword)
        break;
    case 'accountsName':
        searchByAccountsName($scope.searchKeyword)
        break;
    }
};

So what I am trying now is to change the dropdown menu to multiple selected checkboxes and if for example both users-usernames and accounts-name are selected to call the function in the controller searchByUsersUsernameAccountsName($scope.searchKeyword).

1

There are 1 answers

4
Umair Farooq On BEST ANSWER

You can show the check boxes through an array of objects from the controller scope with an attribute bounding to the checkbox value. And inside the search function you check for that attribute value for each object that is bound to check boxes.

Here is the code example I have in mind.

In controller

$scope.checkboxes = [ 
{ checked: false, value: "Username", url_key: "searchAccountsName" },
{ checked: false, value: "Accounts Name", url_key: "searchUsersU‌​sername" } ];

Now in your HTML file, render those check boxes through ng-repeat

<div class="ui fluid action large input">
   <input type="text" placeholder="Search Keyword..." ng-model="searchKeyword">
   <div class="checkboxes">
      <div ng-repeat="checkbox in checkboxes">
          <input type="checkbox" ng-model="checkbox.checked"/> {{checkbox.value}}
      </div>
   </div>
</div>

Now in your search function in controller

$scope.search = function () {
  var urlParams = "";
 for (var i = 0; i < $scope.checkboxes.length; i++){
   if( $scope.checkboxes[i].checked ){
      urlParams = urlParams + $scope.checkboxes[i].url_key + '=true&'
   }
 }

 var urlParams = urlParams + "searchK‌​eyword="+ $scope.searchKeyword;
 searchFn(urlParams);
}

and in the searchFn, you can just append this urlParams string after the question mark in the url.