Sharing different views with user controllers

I have the following problem, and I would like to find a solution or if I even did it, as I did.

I have the following ui-router configuration:

$stateProvider.state('ListCounterparties', { url:"/counterparties", data: { NavMenuItem : 'Counterparties / Desks' }, views: { '' : { templateUrl:"./app/module_Counterparties/templates/ListCounterparties.html", controller:"CounterpartiesControllerCtrl" }, ' deskLists@ListCounterparties ' : { templateUrl : './app/module_Counterparties/templates/DesksDualListTemplate.html', controller:'DesksControllerCtrl' } } 

In the first unnamed view, there is a table from which I can select a row, and then a method will be called to populate the double list from the second view.

So far I have had both in the same controller, but the controller is getting too big, and I decided that I should separate them.

The double-list filling method in " tableLists @ListCounterparties " is defined in DesksControllerCtrl , but it must be called in CounterpartiesControllerCtrl , since the row select event is in this controller.

The problem is that the areas are not separated and the method is not available for an unnamed view.

Area access in DesksControllerCtrl . I could see that I can get access to the $ parent twice in CounterpartiesControllerCtrl , but I won’t lose that ideal thing to do.

Thanks in advance.

+5
source share
1 answer

Sharing data, methods, etc. between multiple controllers, Angular's way would be to create services (s) . This means that you create, for example. a service that contains all your data and another that provides functionality for multiple controllers. Then just inject them in your controllers:

 var myApp = angular.module('myApp', []); myApp.factory('myGlobalData', function() { return { data: 1 }; }); myApp.factory('myService', function(myGlobalData) { return { increment: function() { myGlobalData.data++; } }; }); myApp.controller('MyCtrlA', function($scope, myGlobalData, myService) { $scope.myGlobalData = myGlobalData; $scope.myService = myService; }); myApp.controller('MyCtrlB', function($scope, myGlobalData, myService) { $scope.myGlobalData = myGlobalData; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <p ng-controller="MyCtrlA"> {{myGlobalData.data}} </p> <p ng-controller="MyCtrlB"> {{myGlobalData.data}} </p> <div ng-controller="MyCtrlA"> <button ng-click="myService.increment()">Increment data in myGlobalData service</button> </div> </div> 
+3
source

Source: https://habr.com/ru/post/1241120/


All Articles