1

Why does the following code not work? I want the $scope.init() function to run on startup. What is the correct way to run code on controller initialization?

app.controller('LoginCtrl', function($scope) {
    $scope.init();

    $scope.init = function() {
        ...
    };

});
4
  • 2
    try put the init() after the function? Commented Oct 16, 2014 at 14:22
  • $scope.init() does not exist from where you are calling it. Call it after setting it, i.e. first $scope.init = function... and then $scope.init(). And you may even not need to put init() in scope, running it inline may suffice. Commented Oct 16, 2014 at 14:23
  • already tried, doesn't make any difference Commented Oct 16, 2014 at 14:23
  • 1
    can you set up plunk to reproduce bug? Commented Oct 16, 2014 at 14:24

2 Answers 2

1

You try to call init() before it has been defined. If you switch it, it works as you can see in this fiddle:

http://jsfiddle.net/gjcotq1y/2/

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope){
    $scope.init = function() {
        alert('Message');
    };
    $scope.init();
    $scope.message = 'Test message';
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could also define init in the controller as you do:

app.controller('LoginCtrl', function($scope) {
    $scope.init = function() {
        ...
    };
});

And then call it from the markup:

<body ng-init='init()'>
...
</body>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.