I want to create a application using asp.net mvc and angular js. I want to use angular routing with asp.net mvc routing. I have created to following application. But there is a problem, i am rendering my views inside ng-view using angular, but when i use $scope objects within the controller it says "undefinded".
Here i have ommited angularjs "#" url navigation using $locationProvider
. If i click on the "Route One" link it perfectly navigate to "one.html" view and render it inside ng-view directive. When i click the "Add" button it should display a alert of what i have entered inside the textbox. But instead, alertbox says it is "undefined".
Please tell me what i have missed here. Or what i am doing is wrong or right. Please help me with this. Thank you.
here is my code.
RouteConfig
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 }
);
}
}
Home/Index view
<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 file
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);
}
})
You need to set the controller for the view:
.when('/routeOne', {
templateUrl: 'partials/one.html',
controller: 'oneController'
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.