2017-01-04 166 views
0

我在加载页面时调用函数时遇到问题。我不确定我应该在html中使用什么标签来运行Angular应用程序。在页面加载运行角脚本

我想从数据库中拉出用户数据并将其显示在表中。当我使用一个按钮来调用函数时,它会工作,但我希望它更加自动化。我已经做了一些研究,并且总是让我使用控制器,但我确定必须有一个更简单的解决方案。

<tbody> 
    <Button ng-click="fetchEveryone();">click</Button> 
     <tr ng-repeat="user in all_users"> 
      <td> 
       <img src="/images/{{user.pic}}" style="height: 50px; width: 50px; border-radius: 100px;"/> 
      </td> 
      <td>{{user.name}}</td> 
      <td>{{user.email}}</td> 
      <td> 
       <select ng-change="" ng-model="selectedMeeting"> 
         <option value="">Select Meeting Type...</option> 
         <option ng-repeat="meeting in meetings">{{meeting}}</option> 
       </select> 
      </td> 
      <td> 
       <button>request</button> 
      </td> 
     </tr> 
</tbody> 

这里是Angular的代码。它向python服务器发出请求。

$scope.fetchEveryone = function(){ 
     var req = { 
      verb: 'getPeople', 
      names: $scope.Allusers 
     } 

     $scope.callAPI(req, function(response){ 
      $scope.all_users = response; 
      $scope.view = 'viewPerson' 
     }); 
} 
+5

有一个答案就在这里 - http://stackoverflow.com/questions/15458609/how-to-execute-angular-controller-function-on-page-load - 你试过吗? –

回答

1

可以使用NG-INIT称其为haakon319在this post建议。否则,你可以在函数定义之后调用它在你的控制器,它将会运行在控制器负载:

function myController($scope){ 
    $scope.callAPI = function(req, callback){ 
     //some function 
    }; 

    $scope.fetchEveryone = function(){ 
     var req = { 
      verb: 'getPeople', 
      names: $scope.Allusers 
     } 

     $scope.callAPI(req, function(response){ 
      $scope.all_users = response; 
      $scope.view = 'viewPerson' 
     }); 
    }; 

    $scope.fetchEveryone(); 

} 

如果你有一个以上的事情需要发生,更好的做法可能是有一个专门的init另外

function myController($scope){ 
    $scope.callAPI = function(req, callback){ 
     //some function 
    }; 

    $scope.fetchEveryone = function(){ 
     var req = { 
      verb: 'getPeople', 
      names: $scope.Allusers 
     } 

     $scope.callAPI(req, function(response){ 
      $scope.all_users = response; 
      $scope.view = 'viewPerson' 
     }); 
    }; 

    function moreBackendCalls(){ 
     //more backend calls 
    }; 

    function init(){ 

     $scope.fetchEveryone(); 
     moreBackendCalls(); 

     //init some variables 
     $scope.test1 = 'new test'; 
     $scope.test2 = 73; 

    } 

    init(); 

} 

,你可以使用init添加范围:函数调用所有需要的功能

$scope.init = function(){ 
    ..... 
} 

通过以下方式和添加到您的HTML:

<tbody ng-init="init()"> 
    ....... 
</tbody> 

然后,它将在带有该html的路由被加载时运行。

相关问题