简体   繁体   中英

Change text color dynamically AngularJS

I struggle thinking "The Angular Way" so this is undoubtedly a simple problem, but I'm trying to have it so when I click a button (which will eventually be colored) the text changes to that color. Here is essentially the code:

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>

I know I could easily use jQuery to select the text I want to work with, but I don't want to do that. Do i need to give my paragraph a model? Any push in the right direction is greatly appreciated - thank you.

You could do this way:

Define ng-class directive and value as colorClass which will be set in the scope.

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

and do:

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

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

and some rules:

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

or with inline style

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

and

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM