【问题标题】:AngularJS Routing IssuesAngularJS 路由问题
【发布时间】:2014-08-21 09:00:39
【问题描述】:

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

这是我的控制器;

(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>

我的 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 视图。

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

谁能给我一些建议?

【问题讨论】:

  • 看起来你定义了两次“userViewer”模块

标签: c# javascript html angularjs angular-routing


【解决方案1】:

在你的控制器中你正在这样做

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

当你把 [] 放在那里时,你正在创建一个新模块。试试

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

引用您现有的。

【讨论】:

    【解决方案2】:
    (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
    }]);
    

    【讨论】:

      【解决方案3】:

      将 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);
      }()); 
      

      【讨论】:

        猜你喜欢
        • 2016-11-09
        • 2015-04-20
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多