简体   繁体   English

在Angular SPA中将Controller添加到index.html

[英]Add Controller to index.html in an Angular SPA

My Angular app has several views. 我的Angular应用有多个视图。 The index.html file which has the <div ng-view></div> also has a header/navbar that has links to each of these views. 具有<div ng-view></div>index.html文件还具有一个标题/导航栏,该标题/导航栏具有指向每个视图的链接。

The $routeProvider is configured to load respective views and their controllers. $routeProvider配置为加载各自的视图及其控制器。

Considering this setup, where each of the views has its own controller, how do I add CSS class="active" to the appropriate link in the header when navigating within the app? 考虑到此设置,每个视图都有其自己的控制器,在应用程序内导航时,如何在标题的相应链接中添加CSS class="active"

Extra Info.: I added ng-click="set_page_id(x)" and ng-class={active: active_page_id === x} to the links and realized there's no controller associated with the index.html . 额外信息:我在链接中添加了ng-click="set_page_id(x)"ng-class={active: active_page_id === x} ,并意识到没有与index.html关联的控制器。 I wrote a jQuery function to make this work by listening to click events but it doesn't work when a view itself calls another view. 我编写了一个jQuery函数,通过侦听click事件来使其正常工作,但是当视图本身调用另一个视图时,该功能不起作用。 I wonder if there's a better, Angular way. 我想知道是否有更好的Angular方法。

You have your main or nav controller with something like: 您有类似以下内容的主控制器或导航控制器:

app.controller('mainCtrl', function($scope, $rootScope, $location) {

  $scope.menu = [
    {label:'Home', route:'/'},
    {label:'About', route:'/about'},
    {label:'Contact', route:'/contact'}
   ]

  $scope.menuActive = '/';

  $rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
   $scope.menuActive = $location.path();
});

});

Then 然后

<li ng-repeat="item in menu" ng-class="{active: item.route == menuActive }"><a href="#{{item.route}}" >{{item.label}}</a> </li> 

Heres a Plunker 继承人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM