2015-03-30 20 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