我有以下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'
});
控制器:
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("/")
放在控制器中。
但是,这一次,由于某种原因,控制器代码不会执行。它仅在刷新页面后运行,即使它已分配给无序列表。有人可以帮忙吗?
答案 0 :(得分:0)
您的路线配置应该是:
$routeProvider.
when('/', {
templateUrl: '/index.html',
controller: 'homeCtrl'
}).
when('/doit', {
templateUrl: 'partials/doit.html',
controller: 'myController'
}).
otherwise({
redirectTo: '/'
});
并且您不需要在两个位置指定控制器名称,即在部分和路由配置中,在配置级别指定就足够了。
doit
视图应该是加载在ng-view标记中的视图,因为它是应用程序的状态。