Angular : ng-init does not run on load

两盒软妹~` 提交于 2020-01-01 08:20:48

问题


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

  })    
})



回答2:


another option is using jquery. It would fit if you depend on many elements. But make sure to load jquery with a version of your choice to project. loading jquery (insert version where it's ...):

<script src="https://code.jquery.com/jquery-..."></script>

the js code:

$(document).ready(function() { 
        alert("do something");
    });


来源:https://stackoverflow.com/questions/24694908/angular-ng-init-does-not-run-on-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!