The same data in multiple views using AngularJS

Maybe there is someone who can help me a little. I need to exchange data between several views. Since this is a school project, I have to use AngularJS, but I'm new to this, and I don't know where to start. The program works as follows:

The user (customers) has the opportunity to reserve a table in the restaurant. (first page)

The user (employees) has the ability to add orders to the reserved table. (second page)

When a customer reserves a table from the first page, the table is added to the second page so that the employee can add orders to it.

Maybe there is someone who can help me a little on the way.

+7
source share
2 answers

Since you're new to angularjs, a simpler approach would be to use $ rootScope to exchange data between your controllers (and the views associated with them). A.

Here is an example:

angular.module('MyApp', []) .config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: '/views/main.html', controller: 'MainCtrl' }) .when('/first-page', { templateUrl: '/views/first.html', controller: 'FirstCtrl' }) .when('/second-page', { templateUrl: '/views/second.html', controller: 'SecondCtrl' }); }]) .controller('MainCtrl', ['$rootScope', function ($rootScope) { // Will be available everywhere in your app $rootScope.users = [ { name: 'Foo' }, { name: 'Bar' } ]; }]) .controller('FirstCtrl', ['$rootScope', '$scope' function ($rootScope, $scope) { // Only available inside first.html $scope.bazUser = { name: 'Baz' }; // Add to global $rootScope.users.push($scope.bazUser); }]) .controller('SecondCtrl', ['$rootScope', '$scope' function ($rootScope, $scope) { console.log($rootScope.users); // [{ name: 'Foo' }, { name: 'Bar' }, { name: 'Baz' }]; }]); 

inside second.html for example

 <ul> <li ng-repeat="user in users">{{user.name}}</li> </ul> 
+6
source

Services are singletones, so when a service is entered for the first time, the code in the factory is called once. I assume that you have a routing table as you are talking about multiple pages.

If you define it

 angular.module('services', []) .factory('aService', function() { var shinyNewServiceInstance; //factory function body that constructs shinyNewServiceInstance shinyNewServiceInstance = shinyNewServiceInstance || {foo:1}; return shinyNewServiceInstance; }); 

The dependency inserts it into your controllers (simplified):

 controller('ACtrl', ['aService', function(aService) { aService.foo += 1; }]); controller('BCtrl', ['aService', function(aService) { aService.foo += 1; }]); 

If you look at aService.foo every time you move between ACtrl and BCtrl, you will see that the value has been increased. The logical reason is that the same shinyNewServiceInstance is in your hand, so you can set some properties in the hash from the first page and use it on the second page.

+11
source

All Articles