簡體   English   中英

動態更改文本顏色AngularJS

[英]Change text color dynamically AngularJS

我努力思考“角度方式”,所以這無疑是一個簡單的問題,但是當我點擊一個按鈕(最終會被着色)時,我正試圖這樣做,文本會變成那種顏色。 這基本上是代碼:

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來選擇我想要使用的文本,但我不想這樣做。 我需要給我的段落一個模型嗎? 任何正確方向的推動都非常感謝 - 謝謝。

你可以這樣做:

將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"};
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM