我正在尝试创建自己的指令以突出显示选定的菜单(我知道可以使用ui-sref和ui-sref-active来完成,但稍后需要扩展指令)。
我无法获取触发指令的元素。我希望能够更改所选菜单的颜色,但它甚至不会触发它的开始。我不明白我在做什么错...
angular.module('app', ['ui.router'])
.config(function($stateProvider) {
$stateProvider
.state('home', {
template: '<h2>HOME</h2>'
})
.state('about', {
template: '<h2>ABOUT</h2>'
})
.state('contact', {
template: '<h2>CONTACT</h2>'
});
})
.directive('isMenuActive', ['$state', function($state) {
return {
restrict: 'A',
scope: {
matches: '=isMenuActive'
},
link: function(scope, element, attrs) {
console.log('trigger directive');
for (var i in scope.matches) {
var match = scope.matches[i];
if ($state.current.name.includes(match)) {
console.log('element', element);
element.addClass('active');
break;
}
}
}
}
}])
.controller('mainCtrl', function($state) {
var vm = this;
vm.menus = [
{
name: 'Home',
route: 'home',
matches: ['home', 'some-other-route']
},
{
name: 'About',
route: 'about',
matches: ['about', 'other-route']
},
{
name: 'Contact',
route: 'contact',
matches: ['contact', 'another-route']
}
];
vm.go = function(route) {
$state.go(route);
}
})
ul {
list-style-type: none;
}
ul li {
display: inline-block;
margin-right: 20px;
cursor: pointer;
font-weight: bold;
}
ul li:hover {
opacity: 0.7;
}
.active a {
color: red;
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.22/angular-ui-router.js"></script>
</head>
<body>
<div ng-controller="mainCtrl as vm">
<ul>
<li ng-repeat="menu in vm.menus" ng-click="vm.go(menu.route)" is-menu-active="menu.matches">
<a>{{menu.name}}</a>
</li>
</ul>
</div>
<div ui-view></div>
</body>
</html>