How to use directive templateUrl with external controller?

1

I'm decoupling some components and I'm not sure when to create a controller linked to the template.

I have for example the Login screen, in my directive I do:

app.directive('appLogin',function(){
  return{
    scope: {},
    restrict:'E',
    templateUrl:'view/usuario/login.html',
    controller: ['$scope', function($scope) {
      console.log($scope.login);
    }],
  };
});

In this way I can get all values from the login screen and perform some action, I would like to do a separation to leave like this:

app.directive('appLogin',function(){
  return{
    scope: {},
    restrict:'E',
    templateUrl:'view/usuario/login.html',
    controller: 'controller/usuario/login.js'
  };
});

This way I would only include one init.js file in index.html and it would load all the modules and controllers I need.

What am I doing wrong? is this the right way to perform angular modularization? I am separating 1 file for Controller and 1 for View.

    
asked by anonymous 20.04.2016 / 16:30

2 answers

2

Although Thavia's solution may work, it will depend on its use. I do not particularly like to use controller explicitly set in directive , or controller with directive , because it loses some of its purpose, to create behavior independent of other areas, but, each case is a case.

But in your code the problem is setting controller . You are referencing the physical file JS and not the controller itself.

app.directive('appLogin',function(){
  return{
    scope: {},
    restrict:'E',
    templateUrl:'view/usuario/login.html',
    controller: 'NomeController',
    controllerAs: 'vm' //!Important! Utilize este apenas se você utilizar controllerAs syntax no seu projeto, se não utilize apenas a opção de cima
  };
});

See the definition of controller , you should reference the name of your controller . Just make sure it's inside the same module, or an already loaded module so you can use it.

    
26.04.2016 / 02:29
1

You can inject controllers into your directive and then use angular.extend to bring the $ scope directive to your directive, for example:

app.controller('ctrlB', function($scope) {

  $scope.bar = 'foo';

});


app.directive('appLogin', function() {
  return {
    scope: {},
    restrict: 'E',
    templateUrl:'view/usuario/login.html',
    controller: ['$scope','$controller', function($scope, $controller)     {


      angular.extend(this, $controller('ctrlB', { $scope: $scope }));
      console.log($scope.bar); // foo



    }]
  };
});
    
26.04.2016 / 01:44