Attempting to enable a checkbox using a controller located in a separate controller

I am attempting to trigger a checkbox from a separate controller. Suppose I have a card called information technology under one controller, and when clicked, it should redirect to another page that contains a checkbox for information technology managed by a different controller, with the box pre-checked upon rendering.

The application's architecture is quite complex, so I won't provide any code snippets here. However, I'm looking for guidance on how to approach this challenge.

This is the controller where I intend to write the logic to mark a checkbox as checked (located within another controller).

angular
  .controller("mycontroller", mycontroller);
  mycontroller.$inject = [
        "$scope"
    ];

    // retrieving data with getData()
        $scope.getData = function (data, type) {
            console.log("what is the data about in getData(data)? ", data)
            $scope.query = data.name;
            if (data.checked == undefined) {
                data.checked = true;
            }
        }

Below, you'll find the controller where the checkbox functionality resides.

angular
    .controller('supplierIntelligenceCtrl', function ($scope, $q, FetchData, dataStore, SharedService,
        $document, $window, $state, $rootScope, $timeout, DataCache,
        $filter, $interval, $localStorage, $http) {

                $scope.getData = function (data, type) {
            console.log("what is the data about in getData(data)? ", data)
            $scope.query = data.name;
            if (data.checked == undefined) {
                data.checked = true;
            }

        }

        $scope.apply = function (type) {
            $scope.select = false;
            $scope.bigres = 0;
            $scope.mobFil = 3;
            $scope.applyFilter(type);
        }

        $scope.disableApply = false;
        $scope.disableApply2 = false;

        $scope.applyFilter = function (type) {
            console.log("this is type: ", type)
            if (type == 'industries') {
                $scope.filters.industries = $scope.industries.filter(function (e) {
                    console.log("this is e: ", e.checked)
                    return e.checked;
                }).map(function (f) {
                    console.log("this is f: ", f)
                    return f.id
                })

                $scope.filters.countries = [];
                if ($scope.countries != undefined) {
                    $scope.countries = $scope.countries.map(function (e) {
                        e.checked = false;
                        return e;
                    })
                }
                $scope.filters.cities = [];
                if ($scope.cities != undefined) {
                    $scope.cities = $scope.cities.map(function (e) {
                        e.checked = false;
                        return e;
                    })
                }
                $scope.start = 0;
                if ($scope.filters.industries.length > 0) {
                    $scope.callBackend();
                    $scope.disableApply2 = true;
                    FetchData.fetchDNBCountriesByIndustries('industries=' + $scope.filters.industries + '&size=').then(function (res) {
                        $scope.disableApply2 = false;
                        $scope.countries = res.data;
                        $scope.countriesPage += 10
                    }, function () {
                        $scope.disableApply2 = false;
                    });
                } else {
                    $scope.callBackend();
                }
            }
            if (type == 'countries') {

                $scope.filters.countries = $scope.countries.filter(function (e) {
                    return e.checked;
                }).map(function (f) {
                    return f.id;
                })
                $scope.filters.cities = [];
                if ($scope.cities != undefined) {
                    $scope.cities = $scope.cities.map(function (e) {
                        e.checked = false;
                        return e;
                    })
                }
                $scope.start = 0;
                if ($scope.filters.countries.length > 0) {
                    $scope.callBackend();
                    $scope.disableApply2 = true;
                    FetchData.fetchDNBCitiesByIndustriesAndCountries('industries=' + $scope.filters.industries + '&countries=' + $scope.filters.countries + '&size=').then(function (res) {
                        $scope.disableApply2 = false;
                        $scope.cities = res.data;
                    }, function () {
                        $scope.disableApply2 = false;
                    })
                } else {
                    $scope.callBackend();
                }
            }
            if (type == 'cities') {
                $scope.filters.cities = $scope.cities.filter(function (e) {
                    return e.checked;
                }).map(function (f) {
                    return f.id
                })
                $scope.start = 0;
                $scope.callBackend();
            }


            if (type == 'classifications') {
                $scope.filters.classifications = $scope.classifications.filter(function (e) {
                    return e.checked;
                }).map(function (f) {
                    return f.statusCode;
                })
                $scope.start = 0;
                $scope.callBackend();
            }
        }

        }

Lastly, here is the HTML containing the checkbox:

<div ng-repeat="data in industries">                                 
   <input id="{{data.id}}in" type="checkbox" aria-invalid="false"
          ng-model="data.checked"
          ng-change="getData(data,'industry')">
  <label for="{{data.id}}in">{{data.name}}</label>
</div>

It's possible that I might be missing something or overlooking a detail. As a newcomer to AngularJS, I need assistance in implementing the feature of routing a button/card to another page while checking a specific checkbox filter.

Any advice would be greatly appreciated. :)

Answer №1

An illustration showcasing how controllers can share an array through a shared service injected by the dependency injector. Changing the checkbox in one controller reflects the change in the other.

angular.module('app', []);

angular.module('app')
  .factory('dataService', [function () {
    return {
      data: [
        { prop: '1', checked: false },
        { prop: '2', checked: false },
        { prop: '3', checked: false },
        { prop: '4', checked: false }
      ]
    };
  }]);

angular.module('app')
  .controller('controller1', ['dataService', function (dataService) {
    this.data = dataService.data;
  }]);

angular.module('app')
  .controller('controller2', ['dataService', function (dataService) {
    this.data = dataService.data;
  }]);
  
angular.module('app')
  .controller('controller3', ['dataService', function (dataService) {
    this.toggleAll = () => {
      dataService.data.forEach(item => item.checked = !item.checked)
    };
  }]);
[ng-controller] { display: inline-block; margin-right: 30px; vertical-align: top; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="controller1 as ctrl">
    <strong>Controller 1</strong>
    <div ng-repeat="item in ctrl.data">
      <label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
    </div>
  </div>
  
  <div ng-controller="controller2 as ctrl">
    <strong>Controller 2</strong>
    <div ng-repeat="item in ctrl.data">
      <label>Item {{item.prop}} <input type="checkbox" ng-model="item.checked"></label>
    </div>
  </div>
  
  <div ng-controller="controller3 as ctrl">
    <strong>Controller 3</strong>
    <div>
      <button ng-click="ctrl.toggleAll()">Toggle all</button>
    </div>
  </div>
</div>

Answer №2

Create a shared service with the industries as a property. Inject this service into both controllers using the dependency injector. The first controller can bind the industries to its view while the second one can modify the checked properties.

Answer №3

When discussing redirection and checking a checkbox, there are a few options you can consider:

  1. Pass the selection 'information technology' in the query string to the redirected page and then check the checkbox
  2. If you have a backend server, store the value in a cookie and retrieve it in your AngularJS application

I trust that this information will be beneficial to you.

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

What's the process for converting offsetX and offsetY pixel coordinates to percentages?

Currently, I am working on a project where I need the offsetX and offsetY coordinates to be displayed in percentage (%) format while hovering over a div element. By default, these coordinates are shown in pixels. Here is an example of the structure: < ...

Prevent the use of exponential notation with double numbers in GWT

Is there a way to remove the exponent from a double on the client side in GWT? public double evaluate(final double leftOperand, final double rightOperand) { Double rtnValue = new Double(leftOperand * rightOperand); //Need code to remove expone ...

Redux: streamlining containers, components, actions, and reducers for seamless organization

Here's the question: When working on a large React/Redux application, what is the most effective and sustainable method for organizing containers, components, actions, and reducers? My take: The current trend leans towards organizing redux elemen ...

Creating dynamic child components in Angular JS 4 using data retrieved from a server-side call is a powerful feature that allows for

Upon launching my application, I retrieve the client's IP address and forward it to the server. The server then provides specific data based on this IP address. Once I receive this data, I determine how many child components should be added to the pa ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

sidebar that appears upon the initial page load

I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

The concept of an undefined property

I encountered this error in my console: index.js:70 Uncaught TypeError: Cannot read property 'searchForm' of undefined at eval (index.js:70) at Module../src/js/index.js (bundle.js:4245) at __webpack_require__ (bundle.js:20) at e ...

Error when navigating to a dynamic parameter path using Angular Router

I'm trying to redirect a user to a path with a unique UUID when they go to the root URL (localhost:4200). However, I encountered the following error: ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'document/4fdb ...

What methods can be employed to reduce additional background tasks when altering a state in a React component?

Trying out Code I experimented with creating a React exercise code that showcases a bus and its seats. Reserved seats are marked in red and cannot be selected, while the remaining seats can be chosen by clicking on them and selecting a gender from a popup ...

Create a dynamic animation effect for the placeholder in an input field that triggers when the user starts typing

Have you ever come across interactive demos like this one? I've noticed that most examples involve creating a new element. parent().append("<span>" + $input.attr('placeholder') + "</span>"); Is there a way to make the placehol ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

Struggling to pass Chai tests with Node and Express.js when trying to handle POST requests

Working through a Chai testing exercise and struggling to pass the POST route tests. Encountering two specific errors: 1) Todo API: POST /v1/todos Issue with creating and returning new todo using valid data: Header 'location' should ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Employing a custom JavaScript function to pass the value as a parameter within the <asp:QueryStringParameter> tag

I have a dilemma with using SelectParameters: <SelectParameters> <asp:QueryStringParameter Name="Store" DbType="String" Direction="Input" QueryStringField="Name" DefaultValue="fetchURL();" ConvertEmptyStringToNull="True" /> </SelectPara ...

Can a TypeScript-typed wrapper for localStorage be created to handle mapped return values effectively?

Is it feasible to create a TypeScript wrapper for localStorage with a schema that outlines all the possible values stored in localStorage? Specifically, I am struggling to define the return type so that it corresponds to the appropriate type specified in t ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Encountering an issue with the UNION operator in Typescript causes an error

Currently, I am utilizing the OR operator within Typescript to designate that a product could be of type ProductI OR CartResponseInterface.Product This is how it is structured: product: ProductI | CartResponseInterface.Product However, when attempting t ...

Utilizing ng-repeat to Display JSON Information

I am having difficulty displaying the JSON data using ng-repeat in a simple app. The console shows that the data in the JSON file is being displayed, but an error [ngRepeat:dupes] is thrown. I am working on this using Google Chrome and Xampp. <html ng- ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...

Steps to Deactivate Dates in React Beautiful Dates Component

I found this amazing Calendar library at . Within the library, I am utilizing the <DatePickerCalendar /> component. Currently, I have stored three dates in an array: [date1, date2, date3] My goal is to disable these specific dates in the calendar s ...