目前我有一个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的等价物。


当前回答

当使用$routeProvider时,你可以解析.state并引导你的服务。也就是说,你要加载控制器和视图,只有在解析你的服务之后:

ui-routes

 .state('nn', {
        url: "/nn",
        templateUrl: "views/home/n.html",
        controller: 'nnCtrl',
        resolve: {
          initialised: function (ourBootstrapService, $q) {

            var deferred = $q.defer();

            ourBootstrapService.init().then(function(initialised) {
              deferred.resolve(initialised);
            });
            return deferred.promise;
          }
        }
      })

服务

function ourBootstrapService() {

 function init(){ 
    // this is what we need
 }
}

其他回答

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

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

你的后退按钮

function Backbutton() {
    RetrievedData = CommonFunctionalityService.retrieveResults();
}
angular.element(document).ready(function () {

    // your code here

});

另一个选择:

var myInit = function () {
    //...
};
angular.element(document).ready(myInit);

(通过https://stackoverflow.com/a/30258904/148412)

试试这个?

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

我永远无法得到$viewContentLoaded为我工作,ng-init应该只在ng-repeat中使用(根据文档),而且如果代码依赖于尚未定义的元素,直接在控制器中调用函数可能会导致错误。

这就是我所做的,而且对我很有效:

$scope.$on('$routeChangeSuccess', function () {
  // do something
});

除非你使用ui-router。然后是:

$scope.$on('$stateChangeSuccess', function () {
  // do something
});