Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 468
Chris Avatar asked Jan 02 '14 21:01

Chris


1 Answers

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"};
}
like image 184
PSL Avatar answered Nov 15 '22 18:11

PSL