$ scope和$ routeParams的角度问题

时间:2015-03-30 20:47:07

标签: javascript angularjs

我试图运行一个函数,如果有人点击提交按钮或者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>

2 个答案:

答案 0 :(得分: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();
});

答案 1 :(得分: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&#39; s Sample App