AngularJS不会切换视图

时间:2015-07-06 22:33:41

标签: javascript html angularjs view

我试图切换视图,一旦"添加"单击按钮(参见下面的代码)。但是,当我点击按钮"添加"时,唯一发生的事情是" / addRecordType" 附加到我的网址末尾浏览器,而不是将其解析为' templates / add-record-type.html' ,因为配置指示它执行。为什么会发生这种情况,我怎么能让它发挥作用?谢谢!

parserconfig.html

<!DOCTYPE html>
<html ng-app='parserconfigApp'>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script src="https://code.angularjs.org/1.3.14/angular-route.min.js"></script>

    <title>Parser Config</title>
</head>

<body>
<div ng-controller='ParserConfigController as parserConfig'>
    <button ng-click="changeView('addRecordType')">Add</button>
</div>
    <script type="text/javascript" src="parserconfigApp.js"></script>
</body>
</html>

parserconfigApp.js

var app = angular.module('parserconfigApp', ['ngRoute']);

app.controller('ParserConfigController', ['$scope', '$location', function($scope, $location){        
    $scope.changeView = function(view) {
        $location.path(view);
    }
}]);


app.controller('AddRecordTypeController', ['$scope', function($scope){
}]);


app.config('$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/recordTypeList', {
                templateUrl: '/parserconfig.html',
                controller: 'ParserConfigController'
            }).
            when('/addRecordType', {
                templateUrl: 'templates/add-record-type.html',
                controller: 'AddRecordTypeController'
            }).
            otherwise({
                redirectTo: '/recordTypeList'
            });
    });

3 个答案:

答案 0 :(得分:0)

when('/addRecordType', {
    templateUrl: 'templates/add-record-type.html',
    controller: 'AddRecordTypeController'
}).

应该是

when('/addRecordType', {
    templateUrl: '/templates/add-record-type.html', // Slash added
    controller: 'AddRecordTypeController'
}).

答案 1 :(得分:0)

使用location.url

        this.changeView = function(viewName){
            $location.url('/' + viewName);
        }

或者你可以使用ui-router,这是一种增强的角度路由器,是angular-route

的流行替代品

http://www.ng-newsletter.com/posts/angular-ui-router.html

答案 2 :(得分:0)

抱歉,我的其他答案没那么有用,我想这可能是你的解决方案。

$location.path(view);

仅在不实际加载新路线的情况下更改您的网址。如果你马上使用

$scope.$apply()

然后你应该转向那条路线。

有关详细信息,请参阅here