Ben Finkel Ben Finkel - 6 months ago 39
Javascript Question

Controller parameter is undefined in my directive link function

I'm trying to do something very simple, using the controller parameter of the link function for my directive, but it's being passed as 'undefined'. Can anyone tell me what I'm missing?

The HTML:

<div ng-app="myApp">
<div ng-controller="SampleCtrl" my-form >
<p> Click count: {{ count }} </p>
</div>
</div>


The Javascript:

myApp.controller('SampleCtrl', function($scope){
$scope.count = 0;

this.init = function(val) {
$scope.count = val;
}
});


myApp.directive('myForm', function() {
var linkFn = function(scope, elem, attrs, ctrl) {

ctrl.init(17); //Error here. ctrl is undefined

elem.bind('click', function() {
scope.$apply(function(){
scope.count++;
});
});
};

return linkFn;
});

Answer

It appears that my directive has to use the Directive Definition Object to return the link function and include a reference to the Controller as the 'controller' parameter of the ddo, like so:

myApp.directive('myForm', function() {

    var linkFn = function(scope, elem, attrs, ctrl) {

        ctrl.init("17"); //This now works, due to my return below


        elem.bind('click', function() {
            scope.$apply(function(){                
                scope.count++;
            });
        });     
    };

    return {
        controller: 'SampleCtrl',
        link:linkFn};
});
Comments