【发布时间】:2015-06-15 23:44:41
【问题描述】:
我已经用 angularjs 构建了一个应用程序,并创建了菜单指令,这些指令根据正在加载的视图应用。
这是我的菜单指令的结构:
angular.module('myApp')
.directive('ogSection1Nav', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '../scripts/directives/section1_nav.html',
controller: function($scope, $location) {
$scope.getClass = function(path) {
var cur_path = $location.path().substr(0, path.length);
if (cur_path === path) {
if($location.path().substr(0).length > 1 && path.length === 1 )
return "";
else
return "currentNav";
} else {
return "";
}
}
}
};
});
模板
<section class="adminMenu">
<nav class="side-nav">
<ul>
<li ng-class="getClass('/section1_summary')"><a href="#/section1_summary"><img title="Summary" src="images/summary.svg" title="Summary" height="25" /><span class="navText">Summary</span></a></li>
<li ng-class="getClass('/section1_spot_list')"><a href="#/section1_spot_list"><img title="Spot List" src="images/postList.svg" title="" height="25" /><span class="navText">Spot List</span></a></li>
<li ng-class="getClass('/section1_volume')"><a href="#/section1_volume"><img title="Volume" src="images/volumeHour.svg" title="" height="25" /><span class="navText">Volume</span></a></li>
<li ng-class="getClass('/section1_location')"><a href="#/section1_location"><img title="Location" src="images/geography.svg" title="" height="25" /><span class="navText">Location</span></a></li>
<li ng-class="getClass('/section1_media_type')"><a href="#/section1_media_type"><img title="Media Type" src="images/mediaType.svg" title="" height="25" /><span class="navText">Media Type</span></a></li>
</ul>
</nav>
</section>
getClass 函数检查当前位置并将其与 li 元素上 ng-class="getClass('/section1_volume')" 中定义的路径进行比较,并将 currentNav 类附加到当前页面。
现在我有一大堆这些菜单指令,不想总是在每个指令中重复相同的功能,所以我设置了一个服务如下:
angular.module('myApp')
.service('MenuState', function($location) {
this.getClass = function(path) {
var cur_path = $location.path().substr(0, path.length);
if (cur_path === path) {
if($location.path().substr(0).length > 1 && path.length === 1 )
return "";
else
return "currentNav";
} else {
return "";
}
};
});
然后我在指令中调用 getClass 函数,如下所示:
angular.module('portalDashboardApp')
.directive('ogAdvertisingMediatracNav', function() {
return {
restrict: 'E',
replace: true,
templateUrl: '../scripts/directives/advertising_mediatrac_nav.html',
controller: function($scope, MenuState) {
$scope.getClass = MenuState.getClass();
}
};
});
但是我收到以下错误:TypeError: Cannot read property 'length' of undefined
我认为这是因为路径变量没有传递给我的服务,但我不确定如何通过各种 ng-class="getClass('/path_name' )">我的菜单模板部分
【问题讨论】:
标签: angularjs dependency-injection angularjs-directive angularjs-service