2015-03-30 43 views
0

我試圖運行一個函數,如果有人點擊提交按鈕或者在routeParams中有一個值(如果用戶點擊頁面,param已經填寫了。)我想要一個函數跑步。我有一個大腦放屁,似乎無法得到這個工作!

myApp.config([ '$routeProvider', function($routeProvider) { 
    $routeProvider.when('/:params?', { 
     templateUrl: 'myTemplate', 
     controller : 'myController' 
    }).otherwise({ 
     redirectTo : '/' 
    }); 
} ]); 

myApp.controller('ipCntrl', function($scope,$log,$http,$q,$routeParams, $location) { 

    $scope.runReport = function() { 
     $location.search({'ip': $routeParams['ip']}) 
    } 


}); 

myApp.controller('myController', function($scope,$log,$http,$q,$routeParams, $location) { 

if ($routeParams['ip']) 
{ 
    $scope.ip = $routeParams['ip']; 
    runMyFunction(); 
} 



<div ng-controller="ipCntrl"> 

      <form ng-submit="runReport()"> 
       <input class="form-control" ng-model="ip"> 

      </form> 
    <div ng-view ></div> 
</div> 

<script type="text/ng-template" id="myTemplate"> 
HI! 
</script> 
+0

現在的問題是什麼?即使沒有線路參數,我猜猜它的運行時間? – 2015-03-30 20:56:49

+1

我在路由器中看不到任何'ip'參數 – 2015-03-30 20:56:52

+0

在控制器的函數中使用$ rootScope。$ on('$ stateChangeStart', function(event,toState,toParams,fromState,fromParams){...})攔截狀態轉換。 https://github.com/angular-ui/ui-router/wiki#state-change-events – 2015-03-30 21:30:27

回答

0

既然你試圖調用按鈕點擊或檢查$routeParams後初始化函數,僅僅包括角控制器代碼使用的是(ipCntrl

myApp.controller('ipCntrl', function($scope,$log,$http,$q,$routeParams, $location) { 

    $scope.runReport = function() { 
     $location.search({'ip': $routeParams['ip']}) 
    } 

    //Just put the if statement here 
    //you're already using the ng-submit to call this function from your form 
    if ($routeParam.ip != null) //other definition check logic 
     $scope.runReport(); 
}); 
0

你能使用...

$rootScope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){ 

    console.log('toState ->'); 
    console.log(toState); 

    console.log('toParams ->'); 
    console.log(toParams); 

    console.log('fromState ->'); 
    console.log(fromState); 

    console.log('fromParams ->'); 
    console.log(fromParams); 

    runMyFunction(); 
}) 

...在你的控制器的函數中攔截狀態轉換和請求URLS($ stateParams)。 見State Change Events

您還有View Load events這可能是有用的。

您還可以攔截Angular的.run()中的狀態更改(並評估請求的路由)。
請參閱.run()ui-router's Sample App