问题
I have 4 files:
- index.html
- logic.js
- controller.js
- homepage.html
index.html
<html ng-app="sample">
<head>
<script src="angular.js"></script>
</head>
<body>
<div>
<div ng-view></div>
</div>
<script src="controller.js"></script>
<script src="logic.js"></script>
</body>
</html>
logic.js
var myapp = angular.module('sample',[]);
myapp.config(function($routeProvider)
{
$routeProvider
.when('/',
{
controller:homepageCtrl,
templateUrl:'homepage.html'
});
});
controller.js
function homepageCtrl($scope){
$scope.name = "ROHIT";}
homepage.html
{{name}}
homepage.html is loading and being displayed correctly by the route but the controller is not being called here when homepage.html is loaded into index.html.
Kindly help me out with this.
Thanks
回答1:
You didn't defined controller in HTML.
Add this line
<div ng-controller = "homepageCtrl">
Suppose it should be in homepage.html
:
<div ng-controller = "homepageCtrl">
{{name}}
</div>
In addition, wrap your controller name with '
logic.js
[EDIT]
Add $inject
to routeProvider:
myapp.config(["$routeProvider",
function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'homepage.html',
controller: 'homepageCtrl'
});
}
]);
回答2:
Controller name must be pass to $routeProvider as a string :
$routeProvider
.when('/',
{
controller:'homepageCtrl',
templateUrl:'homepage.html'
});
来源:https://stackoverflow.com/questions/18914183/angularjs-routing-issue-controller-not-loading