此问题的目标是在当前视图的导航锚点上设置一个活动类,即设置。此活动类的触发器是一个在视图加载时执行的函数,而不是用户的单击。
我相信,通过从导航锚中删除ng-click功能并将其替换为.config - > .when - >我的应用程序的每个路径的.controller我可以创建一个更好的与导航栏的交互。
我有3个观点:
var angApp = angular.module('ang6App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl' //placing the function call here wont work when i use a string also.?
})
.when('/flights', {
templateUrl: 'views/flights.html',
controller: 'FlightsCtrl'
})
.when('/reservations', {
templateUrl: 'views/reservations.html',
controller: 'ReservationsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
MainCtrl中的setActive函数
angular.module("ang6App")
.controller("MainCtrl", function ($scope) {
$scope.setActive = function (type) {
$scope.destinationActive = ""; //sets to null
$scope.flightsActive = "";
$scope.reservationsActive = "";
$scope[type + "Active"] = "active"; //targets and matches varible and sets ng-class to active
};
});
另外2个空控制器
angular.module('ang6App')
.controller('ReservationsCtrl', function ($scope) {
});
angular.module('ang6App')
.controller('FlightsCtrl', function ($scope) {
});
HTML - 如何从锚点中删除ng-click
<body ng-app="ang6App">
<div class="page-container" ng-controller="MainCtrl">
<div class="container">
<ul class="nav nav-pills">
<li ng-class="destinationsActive">
<a ng-click="setActive('destinations')" href="#">Destinations</a>
</li>
<li ng-class="flightsActive">
<a ng-click="setActive('flights')" href="#/flights">Flights</a>
</li>
<li ng-class="reservationsActive">
<a ng-click="setActive('reservations')" href="#/reservations">Reservations</a>
</li>
</ul>
</div>
<div class="container" ng-view=""></div>
</div><!--end of MainCtrl page-container-->
</body>
答案 0 :(得分:3)
我建议使用ngClass
<li ng-class="{active:selected=='destination'}">
<a ng-click="selected = 'destination'" href="#" >Destinations</a>
</li>
<li ng-class="{active:selected=='flight'}">
<a ng-click="selected = 'flight'" href="#/flights">Flights</a>
</li>
<li ng-class="{active:selected=='reservation'}">
<a ng-click="selected ='reservation'" href="#/reservations">Reservations</a>
</li>
现在我们不需要采取行动setActive
。 ngClick
适用于模型($ scope.selected),选择目标值。 ngClass
读取所选内容并为我们应用.active
课程
所以:我们可以设置$scope.selected
默认,无需在加载时触发任何内容,只需在控制器中设置正确的选择...