Demand Routing for Controllers

2

I'm creating an application that uses angularJS and I'm new to this library. My problem is that when I see the way it does $router I understand that there is some way I can also route other angular elements like controllers, services, factories, etc. Does anyone have a solution for me to do something like this:

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"

            });
    });
    
asked by anonymous 19.05.2015 / 16:56

1 answer

1

Actually AngularJS already offers this. And you're already very close to the solution.

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

Then you will tell me:

  

"That's all I know, but what about the services and factories?"

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

In this case you have to inject your dependencies (services / factories) into your controller "contactCtrl".

In other words, the first association you should do is set the controller for the state.

Then you inject the services and factories into the controller you previously defined for that specific route.

I've 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 route dependency injection. Take a look at the RESOLVE topic of this page here link

I hope you have helped:)

    
26.06.2015 / 18:31