Angular : ng-init does not run on load

2019-04-04 15:05发布

问题:

I have seen a few exmaples on stack overflow about this ng-init issue, although I cant seem to find one which references it with the use of a controller.

I have called the function in the controller by having the following in the html file

<div class="tab-container" ng-controller = "ExampleController" ng-init = "init()" >

In the controller:

$scope.init = function(){

        alert("do something");
};

It does run, but it runs before the components have loaded on the screen.

Am i missing something?

Thanks

回答1:

ng-init is supposed to work like this, because it's used to initialize data.

A very simple example:

<ul ng-init="list = [1,2,3,4]">
  <li ng-repeat="l in list"></li>
</ul>

If you are trying to run something while your controller loads, it's actually much simpler than you thought:

app.controller('mainCtrl', function ($scope) {

  var init = function ($scope) {
    // do whatever you need to do to initialize your controller
    $scope.someData = ["Hey", "I'm", "Alive"]
    $scope.otherData = localStorage.getItem('myBackup')
  }

  init()

})

Or even simpler, if you don't need the function (no closures or whatever)

app.controller('mainCtrl', function ($scope) {

  // do whatever you need to do to initialize your controller
  $scope.someData = ["Hey", "I'm", "Alive"]
  $scope.otherData = localStorage.getItem('myBackup')

})

Edit - assuming you're using ngView:
To have the code run on when the page is fully loaded you should set a watcher on the event $viewContentLoaded, like this:

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

app.controller('mainCtrl', function ($scope) {

  // This event is triggered when the view has finished loading
  $scope.$on('$viewContentLoaded', function() {

    $scope.someData = ["Hey", "I'm", "Alive"]
    $scope.otherData = localStorage.getItem('myBackup')      

  })    
})