1

本质上,我试图让按钮设置ng-class在 div 上。按钮是使用数组创建的,ng-repeat并且数组会随着时间的推移而增长。我的想法是基于AngularJS 文档的此页面上的最后一个示例来编写此代码的,该文档不使用带有ng-click. 我是 AngularJS 的新手,仍然试图摆脱我的 jQuery 思维方式,所以如果这不是最好的方法,请告诉我。

jsfiddle: http: //jsfiddle.net/E2GB9/ - 不知道为什么它不渲染引导程序 100% 但它应该没关系..

当我使用开发人员工具检查ng-click后加载时,它看起来是正确ng-click="appliedStyle='example1'"的:但单击按钮并没有设置应用样式。

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;
}
4

2 回答 2

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 中并从模板中取出。保持你的代码分开。

于 2013-10-15T19:16:10.867 回答
1

使用范围'$parent和这个语法:

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

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

于 2013-10-15T19:05:22.040 回答