executing a function from one controller within another controller

I am currently working on a modal where, upon clicking the delete button, I need to execute the delete() function from controller A within controller B

https://i.sstatic.net/HJhGT.png

As part of my refactoring process, I am updating the Todo App example code from the AngularJS website, incorporating my newfound knowledge. https://jsfiddle.net/api/post/library/pure/

For the full project, you can visit my GitHub repository: https://github.com/ahmadssb/Angular-Todo-App/tree/development

app.js

angular.module('todoApp', [
    // modules
    'ui.bootstrap', 
    'ui.bootstrap.modal',

    // controllers
    'todo-list-controller', 
    'modal-controller',
    'modal-instance-controller',

    // directives
    'todo-list-directive'
    // services

]);

todo-list-controller.js

angular.module('todo-list-controller', [])
    .controller('TodoListController', function ($scope, $http) {
        var self = this;
        self.todoList = [];
        $http.get("data/todos.json")
            .success(function (response) {
                self.todoList = response;
            });
        $scope.numberOfdeletedNotes = function () {
            var count = 0;
            angular.forEach(self.todoList, function (todo) {
                count += todo.done ? 1 : 0;
            });
            console.log(count);
            return count;
        };
        $scope.delete = function () {
            var currentTodoList = self.todoList;
            self.todoList = [];
            angular.forEach(currentTodoList, function (todo) {
                if (!todo.done) self.todoList.push(todo);
            });
        };
    });

modal-controller.js

angular.module('modal-controller', [])
    .controller('ModalController', function ($scope, $uibModal, $log) {

        $scope.animationsEnabled = true;

        $scope.open = function (size) {
            var modalInstance = $uibModal.open({
                animation: $scope.animationsEnabled,
                templateUrl: 'templates/modals/delete-modal.html',
                controller: 'ModalInstanceController',
                size: size,
            });
            console.log('open()');
        };
    });

modal-instance-controller.js

angular.module('modal-instance-controller', [])
    .controller('ModalInstanceController', function ($scope, $modalInstance) {
        $scope.ok = function () {
            // Here I intend to invoke delete() from todo-list-controller.js
            $modalInstance.close($scope.$parent.delete());
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    });

delete-modal.html

<div class="modal-header">
    <h3 class="modal-title">Warning!</h3>
</div>
<div class="modal-body" ng-control="TodoListController as todoList">
    <h4>You are about to delete <span><i> {{$scope.$parent.numberOfdeletedNotes()}} </i></span> notes</h4>
</div>
<div class="modal-footer">
    <button class="btn btn-danger" type="button" ng-click="ok()">Delete</button>
    <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>

todo-list-template.html

[![<div class="col-md-12" ng-controller="TodoListController as todoList">
    <h2>TODO App</h2>
    <div class="todoList">
        <span class="numberOfList" ng-controller='ModalController as modal'>
         {{remaining()}} of {{todoList.todoList.length}} remaining  
         <button class="btn-danger btn" ng-click="open()">Delete</button>
         </span>
        <ul class="list" ng-repeat="todo in todoList.todoList">
            <li class="item">
                <input type="checkbox" ng-model="todo.done">&nbsp;
                <span class="todo-{{todo.done}}">{{todo.text}} - {{todo.done}} </span>
            </li>
        </ul>
    </div>
    <div class="newTask">
        <form class="form-group" ng-submit="addTodo()">
            <feildset>
                <input type="text" size="30" class="form-control" ng-model="text">
                <input type="submit" value="submit" class="btn btn-primary">
            </feildset>
        </form>
    </div>
</div>]

Answer №1

To improve your code organization, consider moving all state and state-related functions out of your controller and into a service. A good approach in your situation could be to create a TodoListService that handles the management of a todo list and can be accessed from anywhere within your application. Here's an example:

.service('TodoListService', function($http){
    var state = {
        todoList: []
    };
    $http.get("data/todos.json")
        .then(function (response) {
            state.todoList = response.data;
        });

    // Add any necessary functions here to manipulate the todo list

    return {
        getState: function(){ return state; }
    }
});

By injecting TodoListService into your controllers or other parts of your app, you'll have easy access to read and modify the todo list as needed.

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

Is it possible to execute a program on MacOS through a local HTML website?

Are there any straightforward methods to launch Mac programs using HTML? I've created an HTML page featuring a text field and several buttons. The goal is for users to enter a code (numbers) that will then be copied to the clipboard. By clicking on t ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Incorporate dynamic animations into text wrapping using React

Currently, I am in the process of learning React and have successfully created a flexbox with 6 child containers using the wrap property. Now, I am looking to add animation when the containers wrap onto a new line. I attempted to add a transition animatio ...

Encountering difficulties in constructing next.js version 14.1.0

When attempting to build my next.js application, I use the command npm run build Upon running this command, I encountered several errorshttps://i.sstatic.net/5jezCKHO.png Do I need to address each warning individually or is there a way to bypass them? B ...

What happens when the `.push` command runs the "Undefined" function in jQuery - is it possible to execute a number instead?

My script is quite simple - I'm trying to use the push method to add the result of a function called dNumber into the variable named pattern. However, every time I try this, the result is always "undefined". Oddly enough, when I try pushing just plain ...

Creating seamless transitions between pages using hyperlinks

On the homepage, there are cards that list various policies with a "details" button above them. Clicking on this button should take me to the specific details page for that policy. However, each product can only have one type assigned to it. For instance: ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

What is the best way to effectively integrate jQuery plugins into Node.JS?

Getting Started with Node.JS I recently ventured into the world of Node.JS, leveraging my existing expertise in JavaScript and jQuery. While I successfully installed jQuery using npm install jquery, incorporating plugins into my code has proven to be a bi ...

Modifying the src attribute of an object tag on click: A step-by

So I have an embedded video that I want to dynamically change when clicked on. However, my attempt at doing this using JavaScript doesn't seem to be working. <object id ="video" data="immagini/trailer.png" onclick="trailer()"></object> H ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...

Conceal all video containers once a single one is chosen

Having recently delved into Javascript, I am encountering some difficulties in crafting the correct code for a specific function. The scenario involves multiple div elements, each containing 2 child div elements that switch places upon being clicked. Con ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

Changing an HTML table into an array using JavaScript

Is it possible to transform an HTML table into a JavaScript array? <table id="cartGrid"> <thead> <tr> <th>Item Description</th> <th>Qty</th> <th>Unit Price</th> ...

Retrieve the original state of a ReactJs button from the database

I am completely new to ReactJs and I have a question regarding how to set the initial state of a button component based on data from an SQL database. I am successfully retrieving the data using PHP and JSON, but I am struggling with setting the state corre ...

Packing third-party npm modules with Webpack for seamless integration

Description I am currently working on a project that involves nodejs, TypeScript, and express. The source files with a *.ts extension are being bundled using webpack, while the node_modules folder is excluded using webpack-node-externals. However, when I ...

I'm having trouble keeping my navbar fixed

Having trouble keeping my navigation bar fixed I attempted using the <nav class="fixed-nav-bar> with no success. I also tried adjusting it in CSS, but it still wouldn't stay fixed. <nav role="navigation" class="navbar navbar-default"> ...

Tips for capturing changes in a "count" variable and executing actions based on its value

I have a counter on my webpage and I'm trying to change the style of an element based on the count variable. I tried using the .change action but I haven't been able to get it working. It might not be the right solution. Can anyone provide some ...

What is the process of setting up various initialization parameters for a DataTable?

Here is a snippet of JavaScript code I have been using to initialize a DataTable: $(document).ready(function() { $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', &a ...

An error was encountered while attempting to proxy the request [HPM]

After cloning a GitHub repository, I ran npm i in both the root directory and client directories. I then created a development configuration file. However, when attempting to run npm run dev, nodemon consistently crashes with a warning about compiled cod ...

I am looking to include a popover within my modal using Bootstrap version 3.0.2

Hey there, I'm having an issue where the popover that should be inside the modal is actually appearing outside of it in the top left corner, not visible within the modal itself. Below is my index code: <button type="button" id="example" class="bt ...