我正在学习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>
最佳答案
您应该从 Controller 调用此函数。
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
即使使用正常的 javascript/html,您的函数也不会在页面加载时运行,因为您所做的只是定义该函数,而您从未调用它。这实际上与 Angular 无关,但由于您使用的是 Angular,所以上面的内容将是调用该函数的“Angular 方式”。
显然最好还是在 Controller 中声明该函数。
编辑:实际上我看到了你的“onload”——它不会被调用,因为 Angular 将 HTML 注入(inject)到 DOM 中。 html 永远不会“加载”(或者页面仅加载一次)。
关于javascript - Angularjs对页面加载调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27194805/