Angular : ng-init does not run on load

前端 未结 2 2069
情深已故
情深已故 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:04

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

    A very simple example:

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

提交回复
热议问题