如何在页面加载时执行AngularJS控制器功能? [英] How to execute AngularJS controller function on page load?

查看:272
本文介绍了如何在页面加载时执行AngularJS控制器功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我有一个Angular.js页面,它允许搜索并显示结果.用户单击搜索结果,然后单击后退"按钮.我希望再次显示搜索结果,但是我不知道如何触发搜索执行.这是详细信息:

Currently I have an Angular.js page that allows searching and displays results. User clicks on a search result, then clicks back button. I want the search results to be displayed again but I can't work out how to trigger the search to execute. Here's the detail:

  • 我的Angular.js页面是一个搜索页面,具有一个搜索字段和一个搜索 按钮.用户可以手动键入查询,然后按一个按钮,然后 并触发ajax查询并显示结果.我用搜索字词更新了网址.一切正常.
  • 用户单击搜索结果,然后转到另一个页面-效果也不错.
  • 用户单击后退"按钮,然后返回到我的角度搜索页面,并显示正确的URL(包括搜索词).一切正常.
  • 我已将搜索字段值绑定到URL中的搜索词,因此它包含了预期的搜索词.一切正常.
  • My Angular.js page is a search page, with a search field and a search button. The user can manually type in a query and press a button and and ajax query is fired and the results are displayed. I update the URL with the search term. That all works fine.
  • User clicks on a result of the search and is taken to a different page - that works fine too.
  • User clicks back button, and goes back to my angular search page, and the correct URL is displayed, including the search term. All works fine.
  • I have bound the search field value to the search term in the URL, so it contains the expected search term. All works fine.

如何使搜索功能再次执行而无需用户按下搜索按钮"?如果是jQuery,那么我将在documentready函数中执行一个函数.我看不到等效的Angular.js.

How do I get the search function to execute again without the user having to press the "search button"? If it was jquery then I would execute a function in the documentready function. I can't see the Angular.js equivalent.

推荐答案

一方面,就像@ Mark-Rajcok所说的,您可以使用私有内部函数:

On the one hand as @Mark-Rajcok said you can just get away with private inner function:

// at the bottom of your controller
var init = function () {
   // check if there is query in url
   // and fire search in case its value is not empty
};
// and fire it after definition
init();

您还可以查看 ng-init 指令.实现将非常像:

Also you can take a look at ng-init directive. Implementation will be much like:

// register controller in html
<div data-ng-controller="myCtrl" data-ng-init="init()"></div>

// in controller
$scope.init = function () {
    // check if there is query in url
    // and fire search in case its value is not empty
};

但是要小心,因为角度文档暗示了(自v1.2起)请勿为此使用ng-init.但是imo取决于您应用程序的体系结构.

But take care about it as angular documentation implies (since v1.2) to NOT use ng-init for that. However imo it depends on architecture of your app.

当我想将后端的值传递到有角度的应用程序时,我使用了ng-init:

I used ng-init when I wanted to pass a value from back-end into angular app:

<div data-ng-controller="myCtrl" data-ng-init="init('%some_backend_value%')"></div>

这篇关于如何在页面加载时执行AngularJS控制器功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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