动态更改文本颜色AngularJS

时间:2014-01-02 21:16:15

标签: javascript html angularjs

我努力思考“The Angular Way”,所以这无疑是一个简单的问题,但是当我点击一个按钮(最终会被着色)时,我正试图这样做,文本会变成那种颜色。这基本上是代码:

JS

var myApp = angular.module('myApp', []);

myApp.controller('ColorCtrl', ['$scope', function($scope){

    $scope.changeColor = function(value){
        return {"color:" value };
    }

    $scope.turnGreen = function (){
        //what to do here?
    }

    $scope.turnBlue = function() {
        //and here?
    }
}]);

HTML

<div ng-app="myApp" ng-controller="ColorCtrl">

    <button ng-click="turnBlue()">Make text blue</button>
    <button ng-click="turnGreen()">Make text green</button>

    <p ng-style="changeColor(value)">I should be either green or blue!</p>

</div>

我知道我可以轻松使用jQuery来选择我想要使用的文本,但我不想这样做。我需要给我的段落一个模型吗?非常感谢任何正确方向的推动 - 谢谢。

1 个答案:

答案 0 :(得分:19)

你可以这样做:

将ng-class指令和值定义为colorClass,将在范围内设置。

<p ng-class="customStyle.colorClass">I should be either green or blue!</p>

并且做:

 $scope.customStyle = {};
 $scope.turnGreen = function (){
    $scope.customStyle.colorClass = "green";
}

$scope.turnBlue = function() {
    $scope.customStyle.colorClass = "blue";
}

和一些规则:

.green{
  color:green;
}
.blue{
  color:blue;
}

或内联样式

 <p ng-style="customStyle.style">I should be either green or blue!</p>

$scope.customStyle = {};
$scope.turnGreen = function (){
    //what to do here?
    $scope.customStyle.style = {"color":"green"};
}

$scope.turnBlue = function() {
    $scope.customStyle.style = {"color":"blue"};
}