Good time. Faced such a literacy problem. I have several states that $stateprovider can accept, and all these states have the same template (TemplateURL) and are descendants from the default state (which would be less to write).

Now it looks like this:

 (function () { angular .module("StN") .config(config); function config($stateProvider) { $stateProvider .state("invoice", { url: "/invoice", templateUrl: "/Scripts/js/stn/invoice/invoice.html", controller: "invoiceController as vm" }) .state("invoice.custom", { url: "/castom" }) .state("invoice.search", { url: "/search?Status?Invoice?" }); } })(); 

Depending on the current state, slightly different logic must be executed (in this case, different filtering), this happens at the start of the controller. At the moment it looks like this

 angular .module("StN") .controller("invoiceController", invoiceController); function invoiceController($http, $state) { switch (state.name) { case "invoice.search": //Одна Π»ΠΎΠ³ΠΈΠΊΠ° break; case "invoice.custom": //другая Π»ΠΎΠ³ΠΈΠΊΠ° break; case "invoice.status": //Π΅Ρ‰Π΅ 1 Π»ΠΎΠ³ΠΈΠΊΠ° break; } } 

Because of this, a problem arises, if I need some other functionality depending on the current state , I will have to make such a switch again.

Help please make this code more optimized. Thank.

  • Why not use your controller in every stack? - Grundy
  • it requires the logic of this parent controller. I understand that there is a hint of inheritance. But I can’t imagine how to do controller inheritance in a stateprovidr - simply good
  • without a minimal reproducible example, one cannot say what the hint is about, and whether there are any hints at all. - Grundy
  • Corrected, I think the essence is clear - simply good
  • now it is clearly visible that instead of the common controller invoiceController each state should have its own controller, and the switch is not needed at all - Grundy

1 answer 1

You can make different controllers for tasks and expand it with a basic controller that has common logic with the help of angular.extend . For example:

 module.controller('searchController', ['$scope', '$controller', function ($scope, $controller) { angular.extend(this, $controller('BaseController', {$scope: $scope})); // + Π”ΠΎΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒΠ½Π°Ρ Π»ΠΎΠ³ΠΈΠΊΠ° }]); 
  • Yes, I did just that, only the base controller implemented a little bit differently - simply good