Angularjs routing issue, controller not loading

二次信任 提交于 2020-01-05 12:49:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!