目前我有一个Angular.js页面,允许搜索和显示结果。用户单击搜索结果,然后单击返回按钮。我想再次显示搜索结果,但我不知道如何触发搜索执行。细节如下:

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的等价物。


当前回答

我遇到了同样的问题,只有这个解决方案对我有效(它在加载完整的DOM后运行一个函数)。我使用这个滚动锚后页面已加载:

angular.element(window.document.body).ready(function () {

                        // Your function that runs after all DOM is loaded

                    });

其他回答

调用self initialize函数中的初始化方法。

(function initController() {

    // do your initialize here

})();

试试这个?

$scope.$on('$viewContentLoaded', function() {
    //call it here
});

一方面,正如@Mark-Rajcok所说,你可以使用私有内部函数:

// 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指令。实现将很像:

// 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。然而,在我看来,这取决于你的应用程序的架构。

当我想从后端传递一个值到angular app时,我使用了ng-init:

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

你可以使用angular的$window对象:

$window.onload = function(e) {
  //your magic here
}

您可以将搜索结果保存在一个公共服务中,可以从任何地方使用,导航到另一个页面时不清除,然后您可以使用保存的数据设置搜索结果,以便单击后退按钮

function search(searchTerm) {
    // retrieve the data here;
    RetrievedData = CallService();
    CommonFunctionalityService.saveSerachResults(RetrievedData);
} 

你的后退按钮

function Backbutton() {
    RetrievedData = CommonFunctionalityService.retrieveResults();
}