使用AngularJS ng Click和ng Class更改类的按钮

时间:2013-10-15 18:55:28

标签: angularjs angularjs-ng-click

基本上我试图让按钮在div上设置ng-class。按钮是使用ng-repeat从数组创建的,数组将随着时间的推移而增长。我的想法是基于this page of the AngularJS documentation上最后一个不使用ng-click函数的示例编写的。我是AngularJS的新手,仍然试图摆脱我的jQuery思维模式,所以让我知道这不是最好的方法。

jsfiddle:http://jsfiddle.net/E2GB9/ - 不确定为什么它不能100%渲染引导程序但它应该无关紧要..

当我使用开发人员工具检查ng-click后期加载时,它看起来是正确的:ng-click="appliedStyle='example1'"但是点击该按钮不会设置appliedStyle。

HTML:

<body ng-app>
<div ng-controller="TypeCtrl">
<div class="tabbable">
  <ul class="nav nav-tabs">
    <li class="active"><a href="#source" data-toggle="tab">Test Area</a></li>
  </ul>
  <div class="tab-content">
    <div class="tab-pane active" id="source">
        <div class="hero-unit" ng-class="appliedStyle">
        <h1>H1 Header</h1>
        <h2>H2 Header</h2>
        <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
        </div>
    </div>
  </div>
</div>  

    <ul class="unstyled">
        <li ng-repeat="style in styles">
            <span>Name: {{style.name}}</span><br>
            <span>H1: {{style.h1}}</span><br>
            <span>H2: {{style.h2}}</span><br>
            <span>P: {{style.p}}</span><br>
            <button class="btn-small" type="submit" ng-click="appliedStyle='{{style.className}}'">Apply {{style.name}}</button>
        </li>
    </ul>
        The Applied Style is : {{appliedStyle}}
</div>

JS:

function TypeCtrl($scope) {

$scope.styles = [
    {name: 'Example 1', h1:'32px', h2:'24px', p:'12px', className:'example1'}];
}

的CSS:

.example1 h1{
font-size:  10px;
color: red;
}

.example1 h2{
font-size:  8px;
}

.example1 p{
font-size:  6px;
}

2 个答案:

答案 0 :(得分:2)

通过添加如下方法来更改您的控制器:

function TypeCtrl($scope) {

    $scope.styles = [
        {name: 'Example 1', h1:'32px', h2:'24px', p:'12px', className:'example1'}];
    } 

    $scope.applyStyle = function(style) {
        $scope.appliedStyle=style.className;
    }
}

然后在代码中执行此操作:

<button class="btn-small" type="submit" ng-click="applyStyle( style )">

答案很长,带有嵌入式{{}}的javascript不是有效的表达式,因为ng-click使用的$ parse服务不能处理{{}}语法。我只是使用函数,因为你想把你的代码放在Javascript和你的模板之外。保持代码分开。

答案 1 :(得分:1)

使用范围'$parent和此语法:

ng-click="$parent.appliedStyle=style.className"

工作小提琴:http://jsfiddle.net/cherniv/E2GB9/1/