javascript - Controller 中的 Angular 构造函数

标签 javascript angularjs

我尝试过,但没有成功:

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

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

    return PageLayoutController;
});

我正在寻找一种默认或流行的方式来定义这些 Angular Controller 的构造。

我知道我可以创建一个名为 Construct 的函数,然后先调用它,但我想知道是否有官方的方法来做到这一点?

最佳答案

我假设您可能想在 Controller 实例化期间调用定义的函数。如果这是要求,您可以遵循以下语法。

    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();
    });

您还可以监听 $routeChangeStart 事件并调用该函数。

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

您还可以使用以下任何事件。

  • $routeChangeSuccess
  • $routeChangeError

关于javascript - Controller 中的 Angular 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31688421/

相关文章:

javascript - 使用 onclick 调用函数,并在该函数内使用 onclick 调用另一个函数

javascript - 使用 VueJS 和 Skeleton CSS 在 3 次项目迭代后创建新行

javascript - 使用Browserify编译NPM包

javascript - 如何使用on click Angular函数让页面跳转到div?

javascript - 加载最后 3 个和每个新子项

javascript - 右键单击停止传播

javascript - 如何在 MongoDB shell 中将 NumberLong 转换为 Date?

angularjs - 可能未处理的 HTTP 请求拒绝

javascript - 当我使用 AngularJS 部分时如何让 JQuery 工作?

javascript - 从日期时间格式化时间