简体   繁体   中英

How to add a todo from another Controller

I have a todo list in AngularJS that looks like this

 .controller('TodoCtrl', function ($scope) { $scope.todos = [ {text:'Ask smth on Stackoverflow', done:false}, {text: 'Resolve this', done:false} ]; $scope.getTotalTodos = function () { return $scope.todos.length; }; $scope.addTodo = function () { $scope.todos.push({text:$scope.formTodoText, done:false}); $scope.formTodoText = ''; }; $scope.clearCompleted = function () { $scope.todos = _.filter($scope.todos, function(todo){ return !todo.done; }); }; }) 

And I would like to add a Todo (with a text, and a boolean 'done') from another controller that is launched when I click a button. How can I do that ?

A big THANKS to who will help me

Typically services are used to pass information back and forth. Create a service and store your TODO list inside there. Inject that service into both controllers. Each controller can now act on the items in the list

I will append Scotts answer with some shorted Code. Like he said, the best is to use a Service ;) The Service:

.factory('todoService', function() {
    var todolist = [];
    return {
        getTodoList: function() {
            return todolist;
        }
        addTodo: function(todo) {
            todolist.push(todo);
        },
        getTotalTodos: function() {
            return todolist.length;
        },
        // some other
    }
});

Now you can inject the service into any controller via

.controller('TodoCtrl', function ($scope, todoService)

and then you can call the functions of the service in the controller, eg

$scope.addTodo = function () {
    todoService.addTodo({text:$scope.formTodoText, done:false});
    $scope.formTodoText = '';
};

By using Angular Services:

I've made a simple demo.

Hope this helps.

 (function() { var app = angular.module("myApp", []); // myService service.- This service contains an array, called «todos» wich contains data. app.service("myService", function() { return { todos: [{ "text": "Ask smth on Stackoverflow", "done": false }, { "text": "Resolve this", "done": false }] }; }); // Add the dependecy in the controller. app.controller("Controller", ["$scope", "myService", function($scope, myService) { $scope.title = "TODOS"; // This function returns the data stored in the service. $scope.getTodos = function() { return myService.todos; }(); $scope.getTotalTodos = function() { return myService.todos.length; }; // This functions contains the object with the values from the form. $scope.addTodo = function(model) { myService.todos.push({ text: model.text, done: model.done }); $scope.model.text = ""; }; } ]); })(); 
 <html data-ng-app="myApp"> <head> <meta charset="utf-8" /> <title>Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body data-ng-controller="Controller"> <h3>{{title}}</h3> <form id="myForm" ng-submit="addTodo(model)"> <label> Todo <input type="text" data-ng-model="model.text" /> </label> <br /> <label> Done <input type="checkbox" data-ng-model="model.done" /> </label> <br/> <button type="submit">Add</button> <hr /> <ul> <li data-ng-repeat="todo in getTodos"> {{todo.text}} ({{todo.done}}) <input type="checkbox" data-ng-model="todo.done" /> </li> </ul> </form> </body> </html> 


Update: Using the service in multiple controllers.

 (function() { var example = angular.module("starter", []) example.service("todoService", function() { return { todos: [], addTodo: function($text, $classe) { this.todos.push({ text: $text, done: false, }); } }; }); example.controller('nationsLeaguesCtrl', function($scope, todoService) { $scope.randomNationsLeagues = function() { var text = "Text 1"; todoService.addTodo(text, null); }; }) example.controller('statsCtrl', function($scope, todoService) { $scope.randomStats = function() { var text = "Text 2"; todoService.addTodo(text, null); }; }) example.controller('specialCtrl', function($scope, todoService) { $scope.randomSpecial = function() { var text = "Text 3"; todoService.addTodo(text, null); }; }) example.controller('TodoCtrl', function($scope, todoService) { $scope.getTodos = function() { return todoService.todos; }(); $scope.getTotalTodos = function() { return todoService.todos.length; }; $scope.clearCompleted = function() { $scope.todos = _.filter($scope.todos, function(todo) { return !todo.done; }) }; }); })(); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="starter"> <button class="button button-full button-light" ng-controller="nationsLeaguesCtrl" ng-click="randomNationsLeagues()">Nations & Leagues</button> <button class="button button-full button-light" ng-controller="statsCtrl" ng-click="randomStats()">Stats</button> <button class="button button-full button-light" ng-controller="specialCtrl" ng-click="randomSpecial()">Special</button> <div ng-controller="TodoCtrl"> <ul> <li ng-repeat="todo in getTodos">{{todo.text}} <input type="checkbox" name="checkboxG1" id="checkboxG1" ng-model="todo.done" class="css-checkbox" /> <label for="checkboxG1" class="css-label" style="font-family:checkboxFont; color:#ffffff;"><span class="done-{{todo.done}}"></span> </label> </li> </ul> </div> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM