如何使用AngularJS和Angular Bootstrap / UI在Click上添加一个类?

时间:2014-09-15 19:03:02

标签: angularjs twitter-bootstrap

我在这方面与自己的斗争,努力学习。

我有一个Bootstrap菜单......这是其中的一部分:

<div id="language_menu" class="dropdown" on-toggle="toggled(open)">
    <a class="dropdown-toggle" ng-model="clicked"> <span class="flag-xs flag-us"></span> <span class="small va-m">US</span> <i class="fa fa-angle-down"></i> </a>
    <ul class="dropdown-menu">
        <li><a href="javascript:void(0);"><span class="flag-xs flag-in"></span> Hindu</a></li>
        <li><a href="javascript:void(0);"><span class="flag-xs flag-tr"></span> Turkish</a></li>
        <li><a href="javascript:void(0);"><span class="flag-xs flag-es"></span> Spanish</a></li>
    </ul>
</div>

这是我的控制器的一部分:

$scope.toggled = function(open) {
    if (open) {
        $('#language_menu').find('.dropdown-menu').addClass('animated-shortest animated flipInX');
    } else {
        $('#language_menu').find('.dropdown-menu').removeClass('animated-shortest animated flipInX');
    }
};

我对此最好的方法感到困惑。 ngClick vs在切换函数中的控制器上处理它?你可以通过jQuery看到我想要实现的目标。我知道这是错的,或者我正在跳过处理它的角度方式......

请原谅我,因为我对Angular来说是全新的。

----更新----

以这种方式处理它会被认为是不恰当的吗?

<div id="language_menu" class="dropdown" on-toggle="toggled(open)" >
    <a class="dropdown-toggle" href="#"> <span class="flag-xs flag-us"></span> <span class="small va-m">US</span> <i class="fa fa-angle-down"></i> </a>
    <ul class="dropdown-menu {{theClass}}">
        <li><a href="javascript:void(0);"><span class="flag-xs flag-in"></span> Hindu</a></li>
        <li><a href="javascript:void(0);"><span class="flag-xs flag-tr"></span> Turkish</a></li>
        <li><a href="javascript:void(0);"><span class="flag-xs flag-es"></span> Spanish</a></li>
    </ul>
</div>

$scope.toggled = function(open) {
    if (open) {
        $scope.theClass = 'animated-shortest animated flipInX';
    } else {
        $scope.theClass = '';
    }
};

2 个答案:

答案 0 :(得分:1)

使用ngClass:

<div id="language_menu" ng-class="{'animated-shortest animated flipInX': open}" on-toggle="toggled(open)">

</div>

答案 1 :(得分:1)

ngClass会有所帮助。这是一个有效的例子:http://jsfiddle.net/tgg4eq4j/

一些代码: HTML:

<div ng-app="TestApp" ng-controller="TestCtrl">
    <button ng-click="toggle()">Toggle</button>
    <span ng-class="getClass()">I'm toggled</span>
</div>

和JS:

var app = angular.module("TestApp", []);

app.controller("TestCtrl", ["$scope", function ($scope) {
    var flag = true;
    $scope.getClass = function () {
        return flag ? "whitesmoke": "white";
    }

    $scope.toggle = function () {
        flag = !flag;
    };

    $scope.class = "whitesmoke";
}]);