AngularJS路由问题

本文关键字:问题 路由 AngularJS | 更新日期: 2023-09-27 18:10:57

我似乎无法在具有属性"ng view"的div中显示任何内容。

这是我的控制器;

(function () {
var app = angular.module("userViewer", []);
var MainController = function ($scope, $location) {
    console.log("Main controller");
    $scope.search = function () {
        console.log("User ID: " + $scope.userid);
        //Right Route Here
    };
};
app.controller("MainController", MainController);
}());    

这是我的app.js:

(function() {
var app = angular.module("userViewer", ['ngRoute']);
console.log("Test route");
app.config(function($routeProvider) {
    $routeProvider.when("/main", {
            templateUrl: "html/main.html",
            controller: "MainController"
        })
        .otherwise({ redirectTo: "/main" });
});
}());

我的主模板:

<!DOCTYPE html>
<html ng-app="userViewer" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    @Scripts.Render("~/bundles/angular")
</head>
<body>
    @RenderBody()
</body>
</html>

我的angular SPA主页html正文:

<h2>Header</h2>
<div ng-view>
</div>

My main.html

<div>
    <form name="searchUser" ng-submit="search()">
        <input type="search" required ng-model="userid" placeholder="User ID to find" />
        <input type="submit" value="Search" />
    </form>
</div>

我在app.js中的console.log"测试路线打印出来,但当我导航到URL/#/main时,什么都不显示

只有单词"Header"和main.html视图不会在目录中加载。

控制台中也没有显示任何错误。

有人能给我一些建议吗?

AngularJS路由问题

在控制器中执行此

var app = angular.module("userViewer", []);

当您将[]放入其中时,您正在创建一个新模块。尝试

var app = angular.module("userViewer");

以引用您现有的。

(function() {
var app = angular.module("userViewer", ['ngRoute']);
console.log("Test route");
app.config(function($routeProvider) {
    $routeProvider.when("/main", {
            templateUrl: "/html/main.html", <-- try to locate the view starting from the root path of the app
            controller: "MainController"
        })
        .otherwise({ redirectTo: "/main" });
});
}());

尝试将您的控制器定义为:

angular.module('userViewer').controller('MainController', ['$scope', '$location', function ($scope, $location) {
    //your code here
}]);

将app.js更改为

(function () {

    var MainController = function ($scope, $location) {
        console.log("Main controller");
        $scope.search = function () {
            console.log("User ID: " + $scope.userid);
            //Right Route Here
        };
    };
app.controller("MainController", MainController);
}());