0

So, my impression is that Angularjs can be a bit verbose and I would like some clear understanding of what the main differences are between the following functionality AND when are they used. I 'feel' I understand, but lines are a bit vague & ethereal so I want others to clarify.

  1. What is the difference in usage between: They seem interchangeable in their duties, and usage.

    A. Service

    B. Factory

    C. Provider

  2. What is the difference between a module.controller vs. module.directive.controller? ie:


var app = angular.module("someApp",[]);
app.controller("someCtrl1", function(){
       // some code
});

and this usage, when it sits inside a directive

app.directive("someDirective", function() {
  return {
    restrict: 'E',
    template: '<p>Hello {{name}}!</p>',
    controller: function($scope, $element){
      $scope.name = $scope.name + "post1 ";
    },
    link: function(scope, el, attr) {
      scope.name = scope.name + "post2 ";
    }
  }
}) 

I am a little hazy on the "controller" inside the return of the directive. What is this convention, in more detail?

jww
  • 97,681
  • 90
  • 411
  • 885
james emanon
  • 11,185
  • 11
  • 56
  • 97

2 Answers2

1
  1. In a brief, Service is a wrapper for factory and factory is a wrapper for provider. the service uses a JS constructor syntax while factory uses a JS function syntax. BUT, there is one big difference between service/factory and a provider, that the provider is accessible during the config phase while the previous are not. See this good and detailed answer.

  2. The main purpose of a controller in a directive, is when your directive has a isolated scope, so it isn't coupled to the parent controller and therefore it has a independent controller.

Community
  • 1
  • 1
ronen
  • 1,460
  • 2
  • 17
  • 35
1

1.

You can find a clear answer on this question

Additionaly I can say:

Services : has simple structure

Factories has complicated structure

Providers has more complicated structure

  1. There is no differance between module.controller vs. module.directive.controller.

I did't hear about usage module.directive.controller, Correct usage is;

app.directive("myDir", ['$yourService',function($yourService){
   return {
      controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            var that = this;
            //add sume property

            that = angular.extend(that, $yourService));
            return that;
        }]
   }
}])

Basicaly, you don't need controller property for each directives. However, if your directive is a terminal directive or a parent directive, and your child directive need some functions or properties of parent directive, you need a custom contoroller in directive.

For example, if you have table directive which have child row and cell directive, table must hava a controller.

Community
  • 1
  • 1
Mehmet Otkun
  • 1,374
  • 9
  • 22