Html 单击更改ng重复生成的类
我有一个从控制器生成的菜单,当我在某个url(我使用ngRoutes)时,我想在相应的菜单项上添加一个类。该菜单是从Html 单击更改ng重复生成的类,html,angularjs,Html,Angularjs,我有一个从控制器生成的菜单,当我在某个url(我使用ngRoutes)时,我想在相应的菜单项上添加一个类。该菜单是从$scope.menu对象生成的,因此我想我应该向它添加一个样式属性,在单击链接时更新它 现在我被卡住了,因为我需要在每次单击链接时遍历整个对象,将所有样式属性设置为idle,然后将单击的锚的属性设置为高亮显示的 对于jQuery,我想我会使用$(this),但我不知道如何使用angular 我的html: <div class="header" ng-controller=
$scope.menu
对象生成的,因此我想我应该向它添加一个样式属性,在单击链接时更新它
现在我被卡住了,因为我需要在每次单击链接时遍历整个对象,将所有样式属性设置为idle
,然后将单击的锚的属性设置为高亮显示的
对于jQuery,我想我会使用$(this)
,但我不知道如何使用angular
我的html:
<div class="header" ng-controller="NavbarController">
<ul>
<li ng-repeat="link in menu" class="{{link.style}}"><a ng-href="{{link.href}}">{{link.item}}</a></li>
</ul>
</div>
控制员:
'use strict';
angular.module('angularApp')
.controller('NavbarController', function ($scope) {
$scope.menu = [
{
item: 'articles',
href: '#/articles',
style: 'highlighted'
},
{
item: 'sites',
href: '#/sites',
style: 'idle'
},
{
item: 'contact',
href: '#/contact',
style: 'idle'
},
{
item: 'forum',
href: '#/forum',
style: 'idle'
},
{
item: 'account reviews',
href: '#/account_reviews',
style: 'idle'
},
{
item: 'login',
href: '#/login',
style: 'idle'
}
]; // end $scope.menu
$scope.setMenuStlye = function() {
for(x=0; x<$scope.menu.length; x++) {
}
}
});
“严格使用”;
angular.module('angularApp')
.controller('NavbarController',函数($scope){
$scope.menu=[
{
项目:'条款',
href:“#/articles”,
样式:“突出显示”
},
{
项目:'站点',
href:“#/sites”,
风格:“闲散”
},
{
项目:“联系人”,
href:“#/contact”,
风格:“闲散”
},
{
项目:"论坛",,
href:“#/论坛”,
风格:“闲散”
},
{
项目:“账户审查”,
href:“#/account_reviews”,
风格:“闲散”
},
{
项目:“登录”,
href:'#/login',
风格:“闲散”
}
];//结束$scope.menu
$scope.setMenuStlye=函数(){
对于(x=0;x使用ngClass
:
<li ng-repeat="link in menu" ng-class="{highlighted: url === link.item}"><a ng-href="{{link.href}}">{{link.item}}</a></li>
这里有一个快速的例子
$scope.menuClass=函数(第页){
var current=window.location.hash.substring(1.replace(“/”,”);
console.log(当前)
返回页面===当前“活动”:;
};
您可以将所需的类作为函数参数传递到helper函数中。
无论如何,我强烈建议您开始使用,因为它提供了现成的功能。这将返回一个错误“错误:[$parse:syntax]语法错误:Token':'是表达式[highlighted:url===link.item]第12列的意外标记,从[:url==link.item]开始.
。您在ng类上也使用了单大括号而不是双大括号。@MihaŠušteršičng类不使用双大括号。您是否使用了双大括号?因为这可能是导致错误的原因。@MihaŠušteršič更新了答案,您还必须在控制器中包含子字符串以获取原始哈希字符串。还要确保分号后面有空格。如果没有,可能会把东西扔掉。
.controller('NavbarController', function ($scope) {
$scope.url = window.location.hash.substring(2);
}
<li ng-repeat="link in menu" ng-class="menuClass(link.item)"><a ng-href="{{link.href}}">{{link.item}}</a>
$scope.menuClass = function (page) {
var current = window.location.hash.substring(1).replace("/", "");
console.log(current)
return page === current ? "active" : "";
};