Controller parameter undefined in my link function

I am trying to do something very simple using the controller parameter of the link function for my directive, but passed as "undefined". Can someone tell me what I am missing?

HTML:

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

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;
});
+4
source share
3 answers

It seems like my directive should use the directive definition object to return the link function and include the reference to the controller as the "controller" ddo parameter, for example:

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};
});
0
source

How Dan correctly asks in his comment on the accepted answer

- ? ?

, ctrl .

require: 'ngModel'

ng-controller, .

, , , .

myApp.directive('maxFileSize', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            var maxSize = Number(attrs.maxFileSize);

            var sizeHandler = function () {
                if (element.get(0).files.length) {
                    var fileSize = element.get(0).files[0].size; // in bytes
                    if (fileSize > maxSize) {
                        //console.log('file size is more than ' + maxSize + ' bytes!');

                        ctrl.$setValidity("fileSize", false);
                    } else {
                        ctrl.$setValidity("fileSize", true);
                    }
                }
            };

            element.bind('change', sizeHandler);
        }
    };
});
+2

, , , Plunk?

+1
source

Source: https://habr.com/ru/post/1541889/


All Articles