簡體   English   中英

Angularjs頁面加載調用函數

[英]Angularjs on page load call function

我正在學習AngularJS 我有一些文章標簽,點擊一個按鈕,每個文章頁面都顯示沒有任何頁面刷新。 這是一個頁面的網站。 我想要的是當加載文章ID“showSelector”時我想調用myFunction()並在這個函數中我想顯示一個警告。 但警報沒有顯示。

我怎樣才能做到這一點?

 <article id="showSelector" class="panel" ng-controller="CinemaCtrl" onload="myFunction()">
      <header>
        <a ng-click="back()" class="icon fa-arrow-circle-left"></a><h2>Shows in {{getSelectedCinema()}}</h2>        
      </header>
      <p>
        These shows are played in our single room theatre. Select one to reserce a ticket for it.
      </p>
      <section>
        <div class="row">
          <div class="4u" ng-repeat="show in shows">
            <div class="movieCard">
              <a ng-click="selectShow(show)"></a>
              <h3>{{show.nameOfShow}}</h3>
              <h4>{{show.timeOfShow | date:'MMM d'}}</h4>
              <h4>{{show.timeOfShow | date:'HH:mm'}}</h4>
              <p>Free seats: {{show.reservations | freeSeatFilter}}</p>
            </div>
          </div>
        </div>
      </section>
      <script>
function myFunction() {
    alert("Page is loaded");
};
</script>
    </article>

您應該從控制器調用此函數。

angular.module('App', [])
  .controller('CinemaCtrl', ['$scope', function($scope) {
    myFunction();
  }]);

即使使用普通的javascript / html,你的函數也不會在頁面加載時運行,因為你所做的只是定義函數,你永遠不會調用它。 這實際上與角度無關,但由於你使用角度,上面將是調用函數的“角度方式”。

顯然,最好還是在控制器中聲明該功能。

編輯:實際上我看到你的“onload” - 這不會被調用為angular將HTML注入DOM。 html永遠不會“加載”(或頁面只加載一次)。

而不是使用onload,使用Angular的ng-init

<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">

注意:這要求myFunction是CinemaCtrl范圍的屬性。

<section ng-controller="testController as ctrl" class="test_cls"  data-ng-init="fn_load()">

$scope.fn_load = function () {
  console.log("page load")
};

它不是角度方式,從html體中刪除函數並在控制器中使用它,或者使用它

angular.element(document).ready

有關詳細信息,請訪問: https//stackoverflow.com/a/18646795/4301583

您也可以使用以下代碼。

function activateController(){
     console.log('HELLO WORLD');
}

$scope.$on('$viewContentLoaded', function ($evt, data) {
    activateController();
});

您可以直接使用$ scope實例

     $scope.init=function()
        {
            console.log("entered");
            data={};
            /*do whatever you want such as initialising scope variable,
              using $http instance etcc..*/
        }
       //simple call init function on controller
       $scope.init();
    var someVr= element[0].querySelector('#showSelector');
        myfunction(){
        alert("hi");
        }   
        angular.element(someVr).ready(function () {
           myfunction();
            });

這將完成這項工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM