根据 angular 中的路线变化添加或删除 类
adding or removing classes based on route changes in angular
我有 3 条路线,包含 3 种形式
我正在尝试根据 angular.I 中使用的 angular 路由模块中的当前路由在当前选项卡上设置 bootstrap 活动 class。
我怎样才能做到这一点。
我附上js代码请检查并帮助
angular.module('bankAppOnline', ['ngSanitize','ngRoute','ngAnimate','ngQuantum'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/firststep', {
templateUrl: 'templates/firstformtemplate.html',
controller: 'firstformCtrl',
containerClass: 'active'
}).
when('/secondstep', {
templateUrl: 'templates/secondformtemplate.html',
controller: 'secondformCtrl',
containerClass: 'active'
}).
when('/thirdstep', {
templateUrl: 'templates/thirdformtemplate.html',
controller: 'thirdformCtrl',
containerClass: 'active'
}).
otherwise({
redirectTo: '/firststep'
});
}])
.run(function($rootScope){
$rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
console.log(event);
console.log(toState);
console.log(fromState);
console.log(toParams);
$rootScope.containerClass = toState.containerClass;
});
})
.controller('Main-Ctrl',function($scope)
{
$scope.containerClass = "active";
})
.controller('firstformCtrl', function ($scope, Customer) {
$scope.cities = ['Hyderabad','Vizag','Vijayawada','Bangalore','Delhi','Mumbai','Chennai','Noida','Pune','Tirupathi'];
$scope.professions = ['Doctor','Teacher','Engineer','Lawyer'];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.firstform.$setPristine();
var restore = {
"firstname": "",
"lastname": "",
"age": "",
"city": "",
"profession": "",
"mobile": ""
};
angular.extend($scope.customer, restore);
}
})
.controller('secondformCtrl', function ($scope, Customer) {
$scope.designations = ['ChairmanVice Chairman',
'Chairman cum Managing Director',
'Managing Director',
'Sr. Vice president',
'Vice President',
'General Manager',
'Joint General Manager',
'Deputy General Manager',
'Asst. General Manager',
'Chief Manager',
'Sr. Manager',
'Manager',
'Joint Manager',
'Deputy Manager',
'Asst. Manager',
'Sr. Officer',
'Officer',
'Jr. Officer',
'Sr. Associate',
'Associate',
'Jr. Associate',
'Assistant' ];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.secondform.$setPristine();
var restore = {
"pan":"",
"income":"",
"company":"",
"designation":"",
"address":"",
"pin":""
};
angular.extend($scope.customer, restore);
}
})
.controller('thirdformCtrl', function ($scope,$http,Customer,$alert) {
$scope.accounts = ['Savings','Basic checking','Interest-bearing','Market-Deposits','Certificates of deposit'];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.thirdform.$setPristine();
var restore = {
"accountType":"" ,
"fdCheck":false,
"creditcardCheck":false
};
angular.extend($scope.customer, restore);
};
$scope.sendPost = function() {
var data = $scope.customer;
console.log($scope.customer);
$http.post("/users", data).success(function(data, status) {
$scope.status = status;
$alert('form saved successfully.','Oley!', 'success', 'top-right');
console.log($scope.status);
})
.error(function(response, status){
//$alert(options)
//for using more option create object
$alert({title:'Error', content:'An error occured',placement:'top-right',alertType:'danger'});
})
};
})
.factory('Customer', function () {
var customer = {
"firstname": "",
"lastname": "",
"age": "",
"city": "",
"profession": "",
"mobile": "",
"accountType": "",
"fdCheck": false,
"creditcardCheck": false,
"pan": "",
"income": "",
"company": "",
"designation": "",
"address": "",
"pin": ""
};
return {
get: function () {
return customer;
}
}
});
既然你用 angular-ui-router 标记了你的问题,我假设你正在使用它。
使用 UI 路由器 ui-sref 结合 ui-sref-active 可以让您为当前活动状态(或任何子状态)分配 class。
以这里为例。如果状态是 app.tab1(或子状态),active class 将应用于 li 元素。
<ul>
<li ui-sref-active='active'>
<a ui-sref="app.tab1">link</a>
</li>
<li ui-sref-active='active'>
<a ui-sref="app.tab2">link</a>
</li>
<li ui-sref-active='active'>
<a ui-sref="app.tab3">link</a>
</li>
</ul>
见http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active
您可以使用ng-class
这可以使用 ng-class 来实现。只需在控制器中使用 $location 即可。这个例子很简单。这里我们在 $location.path() 等于 '/' 时向 div 添加一个活动的 class.
然后我们在我们的视图中设置一个条件 ng-class,添加活动 class。
查看
<div ng-class="{active: location === '/'}">
<p>The parent DIV will have active class added when location path equals '/'</p>
</div>
控制器
.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeSuccess', function() {
$scope.location = $location.path();
});
});
这是为像我这样的初学者准备的:
HTML:
<script src="~/Content/src/angularjs/angular.min.js"></script>
<script src="~/Content/src/angularjs/angular-route.min.js"></script>
<ul>
<li>
<a ui-sref="Basics" href="#Basics" title="Basics" class="nav-link--link">Basics</a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Coming soon</p>"
})
.when("/Basics", {
templateUrl: "/content/views/Basic.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeSuccess', function () {
navChanged();
});
});
function navChanged() {
setTimeout(function () {
var links = angular.element(document.getElementsByClassName("nav-link--link"));
var activeLink = null;
for (var i = 0; i < links.length; i++) {
var link = links[i]
var linkElement = angular.element(link);
linkElement.removeClass("active");
var hash = location.hash.replace("#/", "#")
if (link.hash && hash.split("#")[1] == link.hash.split("#")[1]) {
activeLink = linkElement;
}
}
activeLink.addClass("active");
}, 100);
};
angular.module('bankAppOnline', ['ngSanitize','ngRoute','ngAnimate','ngQuantum'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/firststep', {
templateUrl: 'templates/firstformtemplate.html',
controller: 'firstformCtrl',
containerClass: 'active'
}).
when('/secondstep', {
templateUrl: 'templates/secondformtemplate.html',
controller: 'secondformCtrl',
containerClass: 'active'
}).
when('/thirdstep', {
templateUrl: 'templates/thirdformtemplate.html',
controller: 'thirdformCtrl',
containerClass: 'active'
}).
otherwise({
redirectTo: '/firststep'
});
}])
.run(function($rootScope){
$rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
console.log(event);
console.log(toState);
console.log(fromState);
console.log(toParams);
$rootScope.containerClass = toState.containerClass;
});
})
.controller('Main-Ctrl',function($scope)
{
$scope.containerClass = "active";
})
.controller('firstformCtrl', function ($scope, Customer) {
$scope.cities = ['Hyderabad','Vizag','Vijayawada','Bangalore','Delhi','Mumbai','Chennai','Noida','Pune','Tirupathi'];
$scope.professions = ['Doctor','Teacher','Engineer','Lawyer'];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.firstform.$setPristine();
var restore = {
"firstname": "",
"lastname": "",
"age": "",
"city": "",
"profession": "",
"mobile": ""
};
angular.extend($scope.customer, restore);
}
})
.controller('secondformCtrl', function ($scope, Customer) {
$scope.designations = ['ChairmanVice Chairman',
'Chairman cum Managing Director',
'Managing Director',
'Sr. Vice president',
'Vice President',
'General Manager',
'Joint General Manager',
'Deputy General Manager',
'Asst. General Manager',
'Chief Manager',
'Sr. Manager',
'Manager',
'Joint Manager',
'Deputy Manager',
'Asst. Manager',
'Sr. Officer',
'Officer',
'Jr. Officer',
'Sr. Associate',
'Associate',
'Jr. Associate',
'Assistant' ];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.secondform.$setPristine();
var restore = {
"pan":"",
"income":"",
"company":"",
"designation":"",
"address":"",
"pin":""
};
angular.extend($scope.customer, restore);
}
})
.controller('thirdformCtrl', function ($scope,$http,Customer,$alert) {
$scope.accounts = ['Savings','Basic checking','Interest-bearing','Market-Deposits','Certificates of deposit'];
$scope.customer = Customer.get();
$scope.reset = function() {
$scope.thirdform.$setPristine();
var restore = {
"accountType":"" ,
"fdCheck":false,
"creditcardCheck":false
};
angular.extend($scope.customer, restore);
};
$scope.sendPost = function() {
var data = $scope.customer;
console.log($scope.customer);
$http.post("/users", data).success(function(data, status) {
$scope.status = status;
$alert('form saved successfully.','Oley!', 'success', 'top-right');
console.log($scope.status);
})
.error(function(response, status){
//$alert(options)
//for using more option create object
$alert({title:'Error', content:'An error occured',placement:'top-right',alertType:'danger'});
})
};
})
.factory('Customer', function () {
var customer = {
"firstname": "",
"lastname": "",
"age": "",
"city": "",
"profession": "",
"mobile": "",
"accountType": "",
"fdCheck": false,
"creditcardCheck": false,
"pan": "",
"income": "",
"company": "",
"designation": "",
"address": "",
"pin": ""
};
return {
get: function () {
return customer;
}
}
});
既然你用 angular-ui-router 标记了你的问题,我假设你正在使用它。
使用 UI 路由器 ui-sref 结合 ui-sref-active 可以让您为当前活动状态(或任何子状态)分配 class。
以这里为例。如果状态是 app.tab1(或子状态),active class 将应用于 li 元素。
<ul>
<li ui-sref-active='active'>
<a ui-sref="app.tab1">link</a>
</li>
<li ui-sref-active='active'>
<a ui-sref="app.tab2">link</a>
</li>
<li ui-sref-active='active'>
<a ui-sref="app.tab3">link</a>
</li>
</ul>
见http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active
您可以使用ng-class
这可以使用 ng-class 来实现。只需在控制器中使用 $location 即可。这个例子很简单。这里我们在 $location.path() 等于 '/' 时向 div 添加一个活动的 class.
然后我们在我们的视图中设置一个条件 ng-class,添加活动 class。
查看
<div ng-class="{active: location === '/'}">
<p>The parent DIV will have active class added when location path equals '/'</p>
</div>
控制器
.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeSuccess', function() {
$scope.location = $location.path();
});
});
这是为像我这样的初学者准备的:
HTML:
<script src="~/Content/src/angularjs/angular.min.js"></script>
<script src="~/Content/src/angularjs/angular-route.min.js"></script>
<ul>
<li>
<a ui-sref="Basics" href="#Basics" title="Basics" class="nav-link--link">Basics</a>
</li>
</ul>
<div ng-app="myApp" ng-controller="MainCtrl">
<div ng-view>
</div>
</div>
Angular:
//Create App
var app = angular.module("myApp", ["ngRoute"]);
//Configure routes
app.config(function ($routeProvider) {
$routeProvider
.otherwise({ template: "<p>Coming soon</p>" })
.when("/", {
template: "<p>Coming soon</p>"
})
.when("/Basics", {
templateUrl: "/content/views/Basic.html"
});
});
//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
$scope.location = $location.path();
$rootScope.$on('$routeChangeSuccess', function () {
navChanged();
});
});
function navChanged() {
setTimeout(function () {
var links = angular.element(document.getElementsByClassName("nav-link--link"));
var activeLink = null;
for (var i = 0; i < links.length; i++) {
var link = links[i]
var linkElement = angular.element(link);
linkElement.removeClass("active");
var hash = location.hash.replace("#/", "#")
if (link.hash && hash.split("#")[1] == link.hash.split("#")[1]) {
activeLink = linkElement;
}
}
activeLink.addClass("active");
}, 100);
};