Retrieve the name of the object within the nested structure

One challenge I'm facing is with the object named '$scope.filter'. It has a nested structure like this:

I am trying to figure out how to retrieve the name of the nested object (key in this case) using a directive. Ideally, I would like to achieve this without involving the controller, but if it's not feasible, then I will consider using the controller.

 <ul>
   <span ng-repeat="x in filter">
    <span ng-repeat="(key,val) in x">


    <span ng-if="x[key]">/*need to extract values of checked checkboxes here  HOW ?*/  </span>



                     </span>
                     </span>

</ul>

This section showcases how checkboxes are created:

<ul ng-repeat="(key,value) in filtered=(properties  | filter: filterByCategory | groupBy: 'name') ">

  <li>Group name: <strong>{{ key }}</strong></li>

          <div  ng-repeat="prop in value">
            <label>
                        <input type="checkbox" ng-model="filter[key][$index]">
                        <span>{{prop.Property}}</span>
            </label>
          </div>
 </ul>

Snippet of the Controller code:

      .controller('dataController', function($scope, $filter)
{
    $scope.properties = [
     {name: 'Weight', Property: 'quintal', value:'50'},
     { name: 'Quantity', Property: 'Litre' , value:'40'},
     { name: 'Quantity', Property: 'ml' , value:'10'},
     { name: 'Height', Property: 'metres' , value:'10' },
     { name: 'Height', Property: 'cm' , value:'20'},
     {name: 'Height', Property: 'inches' , value:'30'},
     { name: 'Size', Property: 'Fat' , value:'28' },
     { name: 'Size',Property: 'Slim', value:'48' },
     { name: 'Feature', Property: 'Sharp' , value:'9'},
     { name: 'Feature', Property: 'Bland', value:'2' },
     {name: 'Weight', Property: 'KG', value:'10'},
     { name: 'Weight', Property: 'grams', value:'20' },
     { name: 'Weight', Property: 'ton' , value:'30'}

];

$scope.filter = {};
$scope.filterByCategory = function (prop) {
  
      angular.forEach($scope.filter, function(item){

    for(key in item)
    {
        if(item[key])
        return;
    else
        console.log("show");
        $scope.filter={};


    }
});

     return $scope.filter[prop.name] || noFilter($scope.filter) ;


    };

Answer №1

I made some adjustments to the structure as your formatting seemed complex for binding:

 $scope.filter = [
    { 
      id: 1,
      groupName: 'Feature',
      options: [
        {id: 1, selected: false },
        {id: 2, selected: false }
      ],
    },
    { 
      id: 2,
      groupName: 'Weight',
      options: [
        {id: 4, selected: false },
        {id: 5, selected: false }
      ],
    },
  ];

You can then create a function in the template to retrieve the name of each option like this:

  $scope.getName = function(group, option) {
    var options = [];
    for (var i = 0; i < $scope.properties.length; i++){
      if ($scope.properties[i].name === group.groupName){
        options.push($scope.properties[i].Property);
      }
    };
    return options[group.options.indexOf(option)];
  };

If you need to extract all selected options from a nested list, you can use a custom filter that will flatten the data into one list. Any required custom logic can be applied in this filter to achieve the desired outcome.
Here's an example of the code:

app.filter('groupFilter', function() {
  return function(filterList, properties) {
    var selectedOptions = [];
    // Loop through all groups
    for (var i = 0; i < filterList.length; i++){
      var group = filterList[i];

      // Get names for properties
      var optionNames = [];
      for (var k = 0; k < properties.length; k++){
        if (properties[k].name === group.groupName){
          optionNames.push(properties[k].Property);
        }
      };

      // Find all selected options in group
      for (var j = 0; j < group.options.length; j++){
        var option = group.options[j];
        if (option.selected){
          selectedOptions.push(group.groupName + ' - ' + optionNames[j]);
        }
      }
    }
    return selectedOptions;
  }
});

With corresponding HTML:

<li ng-repeat="option in filter | groupFilter:properties">{{option}}</li>


You can see both in the sample below:

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attaching a click event to an element located within the template of a directive

I decided to create a reusable directive in order to make a common component, but I am facing an issue trying to capture the click event of an element inside the template used within the directive. Take a look at the code snippet below for better understa ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns? For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests. ...

Is it possible to utilize ag-grid's API to filter multiple checkbox values simultaneously?

I am currently utilizing angularjs and have implemented a series of checkboxes to filter my ag-grid. So far, I have successfully utilized radio buttons and the api.setQuickFilter method for filtering based on individual values. However, I am facing an iss ...

Assigning null values, or initializing values in AngularJS

How can I clear input values to null after clicking on a button? Empty fields: Fields with existing values that I want to reset back to empty fields. HTML: <label class="item item-input"> <input id="tezina" type="number" placeholder ...

Tips for transferring data from one asynchronous function to another in AngularJS

How to transfer a global variable value between two Angular functions? Here are the two global variables: $scope.genewtId = null; $scope.data1 = null; The two Angular functions in question are: $scope.getID = function() { Service1.getId("abc").then(f ...

webdriver: object not found (successfully executes in IDE)

Seeking assistance! I have an input element (shown below) that I am struggling to locate or insert text into. It functions properly in my IDE but not when running my code in Java. The code snippet is as follows: driver.findElement(By.id("searchjobbynam ...

AngularJS: incorporating various functionalities within a single controller

I have a basic AngularJS controller that I am working on, and I would like it to include two separate functions: var app = angular.module('searchApp', []); app.controller('searchCtrl', function($scope, $http, $log) { //Function 1 ...

Click on the button without any reaction

I'm having trouble with the button. When I click on the button with ng-click="goSearchTitle()", nothing happens. Any idea why it's not working? <body ng-app="myapp"> <div ng-contoller="searchbyTitle"> <h3>Sea ...

Animations do not trigger with content changes in AngularJS ngIf

According to the Angular documentation on ngIf, animations occur just after the contents change and a new DOM element is created and injected into the ngIf container. Animations In my experience, I have encountered issues with this behavior. To demonstra ...

Concealing and revealing template URLs with AngularJS

I am currently working with a dynamic Array in my Controller that contains templates (html files) structured similarly to the example below: $scope.templates = [ { name: 'template1.html', url: 'template1.html'}, { name: ...

Best practices for handling multiple tables in AngularJS HTML

How can I loop through multiple tables in AngularJS? Here is an example of my HTML code: <div ng-repeat="stuff in moreStuff"> <table> <h1>{{stuff.name}}</h1> <tr ng-repeat="car in cars"> <td> ...

AngularJS and jQuery offer a convenient way to restrict the selection of future dates in a datepicker

Hello, I am having trouble disabling future dates on my datepicker. I have tried multiple methods but haven't been successful. Can you please point out where I might be going wrong? <div class="input-group date"> <input type="text" clas ...

Having trouble with enabling HTML5 mode to true on an Angular frontend and Laravel backend

I successfully removed the "#!" from my website URL and everything is working perfectly. The only issue I am facing is that when I try to reload a sub URL other than the home page, it shows a "page not found" error. However, I am able to access the same s ...

URLs embedded in a JSON string

Currently, I am using an angular template to display JSON data in a calendar format showing various events. I am wondering if it's possible to include URL links within a string in the JSON data. Here is an example: { "name" : "Lee Morgan", ...

Sorting customization within a complex nested array structure

Sorting a nested array can sometimes be tricky. Consider a JSON structure like the one shown below: var orders = [{ 'orderId': 1, 'sales': [{ 'salesNumbers': 3 }] }, { 'orderId': 2, ...

Executing an external function on an element as soon as it is created in AngularJS: tips and tricks

I am looking to implement a function from an external library that will be executed on each item as it is created in AngularJS. How can I achieve this? Here is the code snippet of my application. var app = angular.module('app', []); app.contr ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...

Ways to prioritize HTML5/CSS3 navigation menu above the content

I am attempting to position my navigation menu on top of the content. Despite using z-index and overflow = visible, the desired effect is not achieved. I want to avoid setting the position relative as it will push the content downwards. Simply put, I want ...

Activate scroll event when image src changes in Angular using jQuery

Seeking assistance with utilizing jQuery to scroll to a specific thumbnail inside a modal when left/right arrows are pressed. The modal should appear when the user clicks on an image. I've managed to implement scrolling upon clicking a thumbnail, but ...