Angular将类添加到活动元素

时间:2013-12-28 15:10:10

标签: css angularjs json menu

如何在这种情况下使用角度将活动类添加到菜单

html代码

<div class="categories" ng-controller="CategoryController">    
  <ul class="menu">     
    <li ng-repeat="category in categories">
      <a ng-click="sendCategory(category)">{{category.name}}</a>
    </li>
  </ul>    
</div>

js code

myApp.factory('Categories', ['$http',      
    function ($http) {      
        return {       
            get: function (callback) {      
                $http.get('data/categories.json').success(function (data) {      
                    callback(data);       
                })       
            }       
        }       
    }       
]);

2 个答案:

答案 0 :(得分:0)

使用以下语法:

<ul class="menu" ng-class="{classname: variableFromScope}">

在控制器中将此变量设置为true或false(以激活或取消激活classname类):

$scope.variableFromScope = true;

答案 1 :(得分:0)

这是解决方案

html代码 <ul class="menu">
<li ng-repeat="category in categories"><a ng-click="sendCategory(category)" ng-class="{ active: activePath=='/{{category.name}}' }">{{category.name}}</a>
</li>
</ul>

js code

`
myApp.controller('CategoryController',函数($ scope,$ route,$ location,$ http,Categories){

Categories.get(function (response) {
    $scope.categories = response;
});

$scope.sendCategory = function (category) {
    $location.path(category.name);
};
$scope.activePath = null;
$scope.$on('$routeChangeSuccess', function () {
    $scope.activePath = $location.path();
    console.log($location.path());
});

})`