Angularjs页面加载调用函数

asd*_*fjk 2 javascript jquery angularjs

我正在学习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>
Run Code Online (Sandbox Code Playgroud)

Jam*_*unt 13

您应该从控制器调用此函数.

angular.module('App', [])
  .controller('CinemaCtrl', ['$scope', function($scope) {
    myFunction();
  }]);
Run Code Online (Sandbox Code Playgroud)

即使使用普通的javascript/html,你的函数也不会在页面加载时运行,因为你所做的只是定义函数,你永远不会调用它.这实际上与角度无关,但由于你使用角度,上面将是调用函数的"角度方式".

显然,最好还是在控制器中声明该功能.

编辑:实际上我看到你的"onload" - 这不会被调用为angular将HTML注入DOM.html永远不会"加载"(或页面只加载一次).


Sco*_*mid 11

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

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

注意:这要求myFunction是CinemaCtrl作用域的属性.