路由在AngularJS中无法正常工作

时间:2015-07-31 05:17:28

标签: javascript angularjs angularjs-routing

我正在尝试在AngularJS中进行路由。当我点击' li' 2,我想显示secondScreen.html的内容。以下是我的代码。我不知道它出了什么问题。谁能告诉我我错过了什么?

AngularJS文件:app.js

var sampleApp = angular.module("sampleApp",['ngRoute','ngResource']);

sampleApp.config(function($routeProvider){

    $routeProvider.when('/',{
        templateUrl : '/templates/firstScreen.html', 
        controller : 'mainController'
    })
    .when('/secondScreen',{         
        templateUrl : '/templates/secondScreen.html', 
        controller : 'mainController'
    })
    .when('/thirdScreen',{          
        templateUrl : '/templates/thirdScreen.html', 
        controller : 'mainController'
    })
    .otherwise({redirectTo : '/'});
});

sampleApp.controller("mainController",["$scope","$log","$resource","$location",function($scope,$log,$resource,$location){

$scope.tabValue = 1;    
$scope.statesAndCapitals = [{state:'Maharashtra',capital:'Mumbai'},{state:'Goa',capital:'Panji'}]

$scope.contacts = [{name:"Steve Jose",mobile : "9872314642",address : "Nasik"}];

$scope.submit = function(tab){
    $scope.tabValue = tab;
    if(tab==1){
        $location.path = '/';
        $log.log("changed path to 1");
    }
    else if(tab==2){
        $location.path = '#/secondScreen';
        $log.log("changed path to 2");
    }
    else if(tab==3){
        $location.path = '#/thirdScreen';
        $log.log("changed path to 3");
    }
}   

$scope.saveContact = function(){

};

}]);

HTML内容:

<body>
    <div ng-controller="mainController">
        <ul>
            <li ng-click="submit(1)" ng-class="{'btn btn-primary' : tabValue==1,'btn btn-default' : tabValue!=1}">Find Capitals</li>
            <li ng-click="submit(2)" ng-class="{'btn btn-primary' : tabValue==2,'btn btn-default' : tabValue!=2}">Add Contact</li>
            <li ng-click="submit(3)" ng-class="{'btn btn-primary' : tabValue==3,'btn btn-default' : tabValue!=3}">Show Contacts</li>            
        </ul>
    </div>
    <div ng-view></div>
</body>

我在更改$ location.path后得到日志。但是没有显示它。

这是我的第二个Screen.html:

<div class="container-fluid">   
<form ng-submit="saveContact()">
    Name : <input type="text"><br/><br/>
    Age : <input type="number" min=1 max=150><br/><br/>
    Gender : 
    <input type="radio" ng-model="gender" ng-value="Male">Male<br/>

    <input type="radio" ng-model="gender" value="Female">Female<br/>
    <input type="submit" value="Submit"/>
</form>

1 个答案:

答案 0 :(得分:1)

使用$location.path('/');

而不是

$location.path="/"

请参阅Docs