AngularJS:初始化控制器时运行代码

AngularJS: Run Code when Controller is initialized

本文关键字:运行 代码 控制器 初始化 AngularJS      更新时间:2023-09-26

为什么以下代码不起作用?我希望$scope.init()函数在启动时运行。在控制器初始化时运行代码的正确方式是什么?

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

您尝试在定义init()之前调用它。如果你切换它,它就会像你在小提琴中看到的那样工作:

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

您也可以在控制器中定义init:

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

然后从标记中调用它:

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