gpt4 book ai didi

javascript - 如何在加载时从 ng-view 的 Controller 触发一个函数——angular

转载 作者:行者123 更新时间:2023-11-29 19:44:23 25 4
gpt4 key购买 nike

这个问题的目标是有一个事件类,即在当前 View 的导航 anchor 上设置。此事件类的触发器是一个函数,它在 View 加载时执行,而不是在用户单击时执行。

我相信,通过从导航 anchor 中删除 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 个额外的空 Controller

angular.module('ang6App')
.controller('ReservationsCtrl', function ($scope) {

});

angular.module('ang6App')
.controller('FlightsCtrl', function ($scope) {


});

HTML -- 我怎样才能从 anchor 中删除 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>

最佳答案

我建议使用 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>

现在我们不需要操作 setActivengClick 使用模型 ($scope.selected),选择预期值。 ngClass 读取选择并为我们应用 .active

因此:我们可以将 $scope.selected 设置为 default,无需在加载时触发任何内容,只需在 Controller 中设置正确的选择...

关于javascript - 如何在加载时从 ng-view 的 Controller 触发一个函数——angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20865889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com