Demand Routing for Controllers

Asked

Viewed 234 times

2

I am creating an application that uses Angularjs and I am new to this library. My problem is that when I see the way it makes the $router i understand that there is a lack of some way that I can also route other angular elements like controllers, services, Factories, etc. By chance someone has some solution for me to do something like:

angular.module("app", ["app.controllers"])
    .config(function($stateProvider) {
        $stateProvider
            .state("contato", {
                url : "/contato",
                templateUrl: "templates/contato.html",

                //isso daqui que precisava
                controller: "contatoCtrl",
                controllerUrl : "controllers/contatoCtrl.js",

                factory: "contatoFtry",
                factoryUrl : "factories/contatoFtry.js",

                service: "contatoSrv",
                serviceUrl : "service/contatoSrv.js"

            });
    });

1 answer

1


In fact Angularjs already offers it. And Angularjs is already very close to the solution.

As Voce is using ui-router, within the ui-router route definition object ($stateProvider) for each Voce state you can set the url, templateUrl and the controller.

Then you’ll tell me:

"Right! That I already know. But what about the services and Factories?!"

The way Voce "route" or associate these other dependencies for each route is through the Controller "contact" that you have already defined.

In this case Voce has to inject its dependencies (services/ Factories) into its controller "contact".

In other words the first association that Voce should do is to define the controller for the route (state).

Then you inject them services and Factories within the controller Voce previously defined for that specific route.

I changed your code. See below:

angular.module("app", ["app.controllers"])
.config(function($stateProvider) {
    $stateProvider
        .state("contato", {
            url : "/contato",
            templateUrl: "templates/contato.html",
            controller: "contatoCtrl"
        });
});


// veja que eu injetei as dependencias contatoFtry e contatoSrv
angular.controller('contatoCtrl', function($scope, contatoFtry, contatoSrv) {
  $scope.mensagem= 'Oi Mundo!';

 // aqui voce pode usar as dependencias injetadas
 // contatoFtry e contatoSrv

});

There are even more powerful features in terms of injecting route dependencies. Take a look at the RESOLVE topic of this page here https://github.com/angular-ui/ui-router/wiki#resolve

I hope it helped :)

  • I started looking about it and ended up finding the Requirejs, that’s just where I understood this dependency issue that angular makes rs, even so thanks friend, that was the conclusion I also found ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.