Angular constructor in a controller

时间:2015-07-28 22:46:57

标签: javascript angularjs

I tried this with no luck:

app.controller('PageLayoutController', function ($scope)
{
    // Scope properties
    $scope.PageMap = {};

    // Constructor
    function PageLayoutController() {
        alert( "contructing" );
    }

    return PageLayoutController;
});

I'm looking for a default or popular way of defining the construct of these controllers in angular.

I'm aware i can just create a function called Construct and then call it first, but i wondered if there was an official way of doing it?

3 个答案:

答案 0 :(得分:3)

I assume you may want to invoke the defined function during Controller getting instantiated. If that's the requirement, you can follow the following syntax.

    angular.module('myApp', [])
    .controller('PageLayoutController', '$scope', function($scope) {
       // Scope properties
       $scope.PageMap = {};

       $scope.PageLayoutController = function() {
          // Do stuffs here
       };

      // Call the function when the Controller get first invoked
      $scope.PageLayoutController();
    });

Also you can listen into the $routeChangeStart event and call the function as well.

$scope.$on('$routeChangeStart', function(next, current) { 
   ... you could trigger something here ...
 });

Also you can use any of the following events as well.

  • $routeChangeSuccess
  • $routeChangeError

答案 1 :(得分:1)

The controller function is already a constructor so anything you write in the its body will be executed on construction.

答案 2 :(得分:1)

Not quite sure what you are exactly trying to do. But being specific, angular instantiates the controller constructor with new operator when it is needed. So what you are trying to do is more of javascript specific question than angular specific. It does it as:

new ctor(); //or new ctor;

had it been new (ctor()) your code will work, but that is not how it happens obviously. The function reference passed in is newed up, not the result of the function execution. So in your case if you were to do this then you need to return the newed up instance. i.e

 return new PageLayoutController;

Example