Angularjs页面加载调用函数
我正在学习AngularJS
。 我有一些文章标签,点击一个按钮,每个文章页面都显示没有任何页面刷新。 这是一个页面的网站。 我想要的是当文章ID“showSelector”被加载时我想调用myFunction()
并在这个函数中我想显示一个警告。 但警报没有显示。
我怎样才能做到这一点?
Shows in {{getSelectedCinema()}}
These shows are played in our single room theatre. Select one to reserce a ticket for it.
function myFunction() { alert("Page is loaded"); };
您应该从控制器调用此函数。
angular.module('App', []) .controller('CinemaCtrl', ['$scope', function($scope) { myFunction(); }]);
即使使用普通的javascript / html,你的函数也不会在页面加载时运行,因为你所做的只是定义函数,你永远不会调用它。 这实际上与角度无关,但由于你使用角度,上面将是调用函数的“角度方式”。
显然,最好还是在控制器中声明该function。
编辑:实际上我看到你的“onload” – 不会被调用,因为angular会将HTML注入DOM。 html永远不会“加载”(或者页面只加载一次)。
而不是使用onload,使用Angular的ng-init
。
注意:这要求myFunction是CinemaCtrl
范围的属性。
$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(); });
这将完成这项工作。