我想在用户角色的基础上创建动态侧边栏。它存储在$ rootScope.login中,但我不知道如何在template.js中使用它
这是我的js代码,对AngularJS来说是一个新手
template.js
$templateCache.put('template/sidebar-left.html',
"<div class=\"sidebar-inner c-overflow\"><div class=\"profile-menu\"><a href=\"\" toggle-submenu><div class=\"profile-pic\"><img src=\"img/profile-pics/1.jpg\" alt=\"\"></div><div class=\"profile-info\">Malinda Hollaway <i class=\"zmdi zmdi-caret-down\"></i></div></a><ul class=\"main-menu\"><li><a data-ui-sref=\"pages.profile.profile-about\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-account\"></i> View Profile</a></li><li><a href=\"\"><i class=\"zmdi zmdi-input-antenna\"></i> Privacy Settings</a></li><li><a href=\"\"><i class=\"zmdi zmdi-settings\"></i> Settings</a></li><li><a href=\"\"><i class=\"zmdi zmdi-time-restore\"></i> Logout</a></li></ul></div><ul class=\"main-menu\"><li data-ui-sref-active=\"active\"><a data-ui-sref=\"home\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-home\"></i> Dashboard</a></li><li data-ui-sref-active=\"active\"><a data-ui-sref=\"timeline\" data-ng-click=\"mactrl.sidebarStat($event)\"><i class=\"zmdi zmdi-layers\"></i>Timeline</a></li>...");
controller.js
this.loginF = function(user) {
$http.post("data/login.php", user).then(function(userData) {
$rootScope.login = userData.data
if( $rootScope.login == "failed" ) {
alert(JSON.stringify($rootScope.login))
} else {
window.location.assign("home.html");
}
})
}
答案 0 :(得分:0)
您应该为此创建一个指令,例如:
app.directive("userMenu", function() {
return {
restrict: "AE",
scope: {
user: "="
},
templateUrl: "template/sidebar-left.html",
link: function($scope, $elem, $attrs) {
$scope.hasRole = function(role) {
if (!$scope.user) {
return false;
}
// assuming the user data model looks something like this:
// { roles: ["admin", "editor"] }
return $scope.user.roles.indexOf(role) > -1;
}
}
}
});
然后在你的侧边栏左侧模板中这样:
<div>
<ul class="menu">
<li ng-if="hasRole('admin')">
<a href="#">This only shows if the user has the role 'admin'</a>
</li>
<li>
<a href="#">This always shows, no matter the role</a>
</li>
</ul>
</div>
然后你可以把它包含在你的HTML中:
<div user-menu user="$root.login"></div>