If you want to use $rootScope in Angular to store variables? Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.
AngularJS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | var app = angular.module('myApp', []); app.factory('items', function() { var items = []; var itemsService = {}; itemsService.add = function(item) { items.push(item); }; itemsService.list = function() { return items; }; return itemsService; }); function Ctrl1($scope,items) { $scope.list = items.list; } function Ctrl2($scope, items) { $scope.add = items.add; } |
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <div ng-controller="Ctrl1"> <h2>Ctrl1 - List</h2> <ul> <li ng-repeat="item in list()">{{item}}</li> </ul> </div> <hr /> <div ng-controller="Ctrl2"> <h2>Ctrl2 - Add</h2> <form ng-submit="add(newItem); newItem = '';"> <input type="text" placeholder="new item..." ng-model="newItem"> <br /> <input class="btn" type="submit"> </form> </div> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.