【发布时间】:2015-05-17 13:19:27
【问题描述】:
我想使用 asp.net mvc 和 angular js 创建一个应用程序。我想将角度路由与 asp.net mvc 路由一起使用。我已经创建了以下应用程序。但是有一个问题,我正在使用 Angular 在 ng-view 中渲染我的视图,但是当我在控制器中使用 $scope 对象时,它会显示“未定义”。
在这里,我使用 $locationProvider 省略了 angularjs "#" url 导航。
如果我单击“Route One”链接,它会完美导航到“one.html”视图并将其呈现在 ng-view 指令中。
当我单击“添加”按钮时,它应该显示我在文本框中输入的内容的警报。但是,alertbox 却说它是“未定义的”。
请告诉我我在这里错过了什么。或者我在做什么是错的还是对的。请帮我解决一下这个。谢谢。
这是我的代码。
路由配置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RoutesDemo",
url: "{*catchall}",
defaults: new { controller = "Home", action = "Index" });
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
主页/索引视图
<html ng-app="MyApp" ng-controller="MyController">
<head>
<meta charset="utf-8">
<base href="/">
</head>
<body>
<h1>{{heading}}</h1>
<ul>
<li><a href="/routeOne">Route One</a></li>
<li><a href="/routeTwo">Route Two</a></li>
<li><a href="/routeThree">Route Three</a></li>
</ul>
<div ng-view></div>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/App/app.js"></script>
</body>
</html>
partials/one.html
<h3>One</h3>
<br />
<input type="text" ng-model="item" />
<input type="button" ng-click="add()" value="Add"/>
partials/two.html
<h3>Two</h3>
partials/three.html
<h3>Three</h3>
app.js 文件
var app = angular.module('MyApp', ['ngRoute'])
.config(function ($routeProvider,$locationProvider) {
$routeProvider
.when('/routeOne', {
templateUrl: 'partials/one.html'
})
.when('/routeTwo', {
templateUrl: 'partials/two.html'
})
.when('/routeThree', {
templateUrl: 'partials/three.html'
});
$locationProvider.html5Mode(true);
});
app.controller('MyController', function ($scope) {
$scope.heading = "Page Heading";
$scope.add = function () {
//here i cant access the $scope item. it says "undefined"
alert($scope.item);
}
})
【问题讨论】:
标签: javascript c# asp.net asp.net-mvc angularjs