Angularjs页面加载调用函数 [英] Angularjs on page load call function

查看:117
本文介绍了Angularjs页面加载调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 AngularJS 。我有一些文章标签,点击一个按钮,每个文章页面都显示没有任何页面刷新。这是一个页面的网站。我想要的是,当加载文章IDshowSelector时,我想调用 myFunction(),在这个函数中我想显示一个警告。但警报没有显示。

I am learning AngularJS. I have some article tag and on clicking on a button each article page is showed without any page refresh. This is one page website. What I want is that when article id "showSelector" is loaded I want to call myFunction() and in this function I want to show an alert. But the alert is not showing.

我该怎么做?

 <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>


推荐答案

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

You should call this function from the controller.

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

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

Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.

显然,更好的还是声明也可以在控制器中运行。

Obviously better still declare the function in the controller too.

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

Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).

这篇关于Angularjs页面加载调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆