如何在页面加载时执行 AngularJS 控制器功能? [英] How to execute AngularJS controller function on page load?
问题描述
目前我有一个 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.一切正常.
- 用户点击搜索结果并被带到不同的页面 - 这也能正常工作.
- 用户单击后退按钮,然后返回到我的 angular 搜索页面,并显示正确的 URL,包括搜索词.一切正常.
- 我已将搜索字段值绑定到 URL 中的搜索词,因此它包含预期的搜索词.一切正常.
如何让搜索功能再次执行而无需用户按下搜索按钮"?如果是 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
};
但请注意它,因为 angular 文档暗示(自 v1.2 起) 不要为此使用 ng-init
.但是,这取决于您应用的架构.
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.
当我想将值从后端传递到 angular 应用程序时,我使用了 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屋!