页面加载调用函数上的 Angularjs

Angularjs on page load call function

本文关键字:Angularjs 函数 调用 加载      更新时间:2023-09-26

我正在学习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,你的函数也不会在页面加载时运行,因为你所做的只是定义函数,你永远不会调用它。 这实际上与角度无关,但由于您使用的是角度,因此上面的"角度方式"将调用该函数。

显然,最好还是在控制器中声明函数。

编辑:实际上我看到你的"加载" - 这不会被调用,因为角度将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();
            });

这将完成这项工作。