How to execute AngularJS controller function on page load?

前端 未结 14 2522
一整个雨季
一整个雨季 2020-11-22 16:04

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 disp

14条回答
  •  情歌与酒
    2020-11-22 16:13

    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();
    

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

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

    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.

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

提交回复
热议问题