Angular : ng-init does not run on load

前端 未结 2 2127
情深已故
情深已故 2021-02-19 19:27

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 t

相关标签:
2条回答
  • 2021-02-19 20:03

    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");
        });
    
    0 讨论(0)
  • 2021-02-19 20:04

    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')      
    
      })    
    })
    
    0 讨论(0)
提交回复
热议问题