Angularjs页面加载调用函数

时间:2014-11-28 19:19:26

标签: 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>

7 个答案:

答案 0 :(得分:13)

您应该从控制器调用此功能。

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

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

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

编辑:其实我看到了你的#34; onload&#34; - 因为角度将HTML注入DOM而不会被调用。 html永远不会被加载&#34; (或页面只加载一次)。

答案 1 :(得分:11)

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

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

注意:这要求myFunction是CinemaCtrl范围的属性。

答案 2 :(得分:3)

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

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

答案 3 :(得分:2)

不是角度方式,从html体中删除函数并在控制器中使用它,或者使用

angular.element(document).ready

此处提供了更多详细信息:https://stackoverflow.com/a/18646795/4301583

答案 4 :(得分:0)

您也可以使用以下代码。

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

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

答案 5 :(得分:0)

您可以直接使用$ scope instance

     $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();

答案 6 :(得分:-3)

    var someVr= element[0].querySelector('#showSelector');
        myfunction(){
        alert("hi");
        }   
        angular.element(someVr).ready(function () {
           myfunction();
            });

这样就可以了。

相关问题