javascriptangularjscontrollerangularjs-controllerangularjs-controlleras

Why are my controllers methods not available?


after a long time I have to concentrate an angular again. But I fail...

... ng-repeat="n in DataController.getObjects"

myApp.controller('DataController', [function () {

    console.log('test 1');

    var getObjects = function () {
        console.log('test 2');
        return [1,2,3,4,5,6,7];
    };

}]);

It is writing test 1 to console but not test 2. And the frontend does not get the array.

Any hint for me?

Regards n00n


Solution

  • You have to expose method/variable which you want to access on page on this(context) of your controller. So that you can access that method/variable via controller alias as you you seems to be using controllerAs pattern.

    Code

    myApp.controller('DataController', [function () {
        var self = this;
        console.log('test 1');
        var getObjects = function () {
            console.log('test 2');
            return [1,2,3,4,5,6,7];
        };
    
        self.getObjects = getObjects;
    }]);
    

    I hope you have already defined controller alias while using ng-controller directive, If you haven't used it, follow below.

    ng-controller="DataController as dataCtrl"
    
    ng-repeat="n in dataCtrl.getObjects()"
    

    And as you can see you should call method in ng-repeat like getObjects() to get a array from method.