如何使用angularjs转到另一个页面

时间:2017-03-28 01:53:02

标签: javascript jquery angularjs url-routing

我正在尝试从网址中的一个页面传递数据并从网址获取新页面,例如我想在网址中添加10,20。就像在给定的例子中我在sumurl中传递10,20它在div ng-view中显示它的总和,但我想在sumurl.html或input.html中显示它

var app=angular.module('myapp',['ngRoute']);
    app.config(['$routeProvider',function($routeProvider){
        
        $routeProvider
            .when('/sumurl/:a/:b',{
            templateUrl:'sumurl.html',
            controller:'sumurl'
        })
            .when('/input',{
            templateUrl:'input.html',
            controller:'input'
        })
            .when('/',{
            template:'Welcome to my app'
        }).otherwise({
            template:'Not Available'
        })
    }]);
    
    app.controller('sumurl',['$scope','$routeParams',function($scope,$routeParams){
        $scope.n1=$routeParams.a;
        $scope.n2=$routeParams.b;
        
    }]);
    
    app.controller('input',['$scope','$location','$interpolate',function($scope,$location,$interpolate){
        $scope.n1=0;
        $scope.n2=0;
        
        $scope.dosum=function(){
            var url=$interpolate('/sumurl/{{n1}}/{{n2}}')($scope);
                //console.log(url);
            $location.path(url);
        }
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div ng-app="myapp">
<ul>
<li><a href="#/sumurl/10/20">some url</a></li>
<li><a href="#/input">input</a></li>
<li></li>
</ul>
    <div ng-view>
    
    </div>
    
</div>

Sumurl和输入是两个html文件

sumurl.html

<div>
    a = {{n1}}<br>
    b = {{n2}}<br>
    Sum = {{(n1-0)+(n2-0)}}
</div>

和input.html

<div>
    n1 = <input type="number" ng-model="n1"/>
    n2 = <input type="number" ng-model="n2"/>
    <button ng-click="dosum()">Sum</button>
    
</div>

1 个答案:

答案 0 :(得分:1)

注入$location服务,然后您可以执行$location.href = <your target URL>