AngularJS:在调用它的按钮上应用动态类

时间:2014-03-07 00:56:18

标签: html css angularjs

抱歉标题可能令人困惑,但我想要做的是根据按钮点击动态更改一个类。但是,除了调用changToRed函数的ons按钮之外,这适用于每个标记。

<div ng-controller="clickCtrl">
    <ons-button ng-class="dynamic" ng-click="changeToRed()">Red</ons-button>
</div>

这是我的main.js文件:

var myApp = angular.module('myApp');

myApp.controller('clickCtrl', function($scope){

$scope.dynamic = "blue";

$scope.changeToRed = function(){
  $scope.dynamic = "red";      
}

$scope.changeToGreen = function(){
  $scope.dynamic = "green";
}

$scope.changeToBlue = function(){
  $scope.dynamic = "blue";      
}

});

谢谢, 本

2 个答案:

答案 0 :(得分:1)

这是AngularJS' scope的问题。这是一篇很长的文章,但你需要的部分是关于范围点符号。将您的控制器更改为:

var myApp = angular.module('myApp');

myApp.controller('clickCtrl', function($scope){
  $scope.model = {};
  $scope.model.dynamic = "blue";

  $scope.changeToRed = function(){
    $scope.model.dynamic = "red";
  }

  $scope.changeToGreen = function(){
    $scope.model.dynamic = "green";
  }

  $scope.changeToBlue = function(){
    $scope.model.dynamic = "blue";
  }
});

然后将HTML更改为:

<div ng-controller="clickCtrl">
    <ons-button ng-class="model.dynamic" ng-click="changeToRed()">Red</ons-button>
</div>

答案 1 :(得分:1)

ons-button在内部使用ng-class。如果您不需要微调器动画,则可以使用类版本。

<button ng-class="dynamic" ng-click="changeToRed()" class="topcoat-button">Red</button>

您还需要在您的CSS中添加!important。

.red {
    background-color: red !important;
}