我有以下 Index.html
文件(我也将 div
和 ng-view
放在一起):
<ul ng-controller="myController">
<li>
<a href="#/doit">Do it!</a>
</li>
</ul>
路由配置:
$routeProvider.when('/doit', {
templateUrl: 'partials/doit.html'
controller: 'myController'
});
$routeProvider.otherwise({
redirectTo: 'index.html'
});
Controller :
app.controller('myController', ['$scope', '$location', function ($scope, $location) {
$scope.name = "name";
alert($scope.name);
$location.path("/");
}]);
奇怪的是,在我点击 Do it!
链接后,它会转到 http://localhost:3000/#/doit.html
( myController
的代码在点击后执行,我看到弹出警报),然后我返回到 http://localhost:3000/#/index.html
(这就是我想要的,我把 $location.path("/")
放在 Controller 里。
然而,这一次,出于某种原因, Controller 代码没有执行。它仅在我刷新页面后运行,即使它已分配给无序列表。有谁能帮忙吗?
最佳答案
你的路由配置应该是这样的:
$routeProvider.
when('/', {
templateUrl: '/index.html',
controller: 'homeCtrl'
}).
when('/doit', {
templateUrl: 'partials/doit.html',
controller: 'myController'
}).
otherwise({
redirectTo: '/'
});
并且您不需要在两个地方指定 Controller 名称,即在部分配置和路由配置中,在配置级别指定就足够了。
doit
View 应该是在 ng-view 标签中加载的 View ,因为它是应用程序的一种状态。
关于javascript - Controller 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395982/