0
votes

I think I am confused about how to properly build custom directives - namely when to use a controller inside a directive. If they use an isolated scope and have properties passed to them from their parent controller this is fine.

However, seeing as I thought directives should be treated as reusable components, it makes sense to have their own controllers to set up helper methods, scope variables etc, like in a regular controller. For instance I have a custom directive and in it's template I use ng-show. The condition checks a scope property using a method I write in the directive's controller.

<div>
    <div ng-show="isLong()"></div>
</div>

In the directive I set up isLong in the controller:

angular.module('myApp')
    .directive('myDirective', [function () {
        return {
            restrict: 'A',
            controller: function($scope, $element, $attrs){
                $scope.isLong = function(){
                    return true;
                }
            }
        };
    }]);

Though I have not found any Angular articles about directives which talk about this use of directives. How should I be using them? And in this above example, from the directive's template how am I supposed to use ng-show?

Any guidance appreciated. I'm trying to use Angular in the right way.

2

2 Answers

0
votes

second argument not correct

angular.module('myApp')
    .directive('myDirective', function () {
        return {
            restrict: 'A',
            controller: function($scope, $element, $attrs){
                $scope.isLong = function(){
                    return true;
                }
            }
        };
    });

if you wont inject different service, you must be injectet them in array

angular.module('myApp')
    .directive('myDirective', ['someService', function (someService) {
        return {
            restrict: 'A',
            controller: function($scope, $element, $attrs){
                $scope.isLong = function(){
                    return true;
                }
            }
        };
    });
0
votes
  1. Directive controllers are executed after the compile phase. This means that by the time any directive controller function runs, all the directives have already been compiled and transformed.

  2. A directive controller function is called before the directive (or any of its children) are linked. This makes it a convenient place to initialize your scope before your directive is linked so that your bindings have well-defined values before their $watch handlers are called for the first time.

Remember, when you define a variable or method in your directive's scope, it is available to participate in data-binding within your directive's HTML. Child directives can also access the directive's scope as long as their scopes are set up to inherit scope prototypically - meaning a scope variable from the parent scope may be inherited by the child scope through scope inheritance.