动态更改文本颜色AngularJS

Chr*_*ris 9 html javascript 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?
    }
}]);
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

PSL*_*PSL 20

你可以这样做:

定义colorClass将在范围中设置的ng-class指令和值.

<p ng-class="customStyle.colorClass">I should be either green or blue!</p>
Run Code Online (Sandbox Code Playgroud)

并做:

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

$scope.turnBlue = function() {
    $scope.customStyle.colorClass = "blue";
}
Run Code Online (Sandbox Code Playgroud)

和一些规则:

.green{
  color:green;
}
.blue{
  color:blue;
}
Run Code Online (Sandbox Code Playgroud)

或者采用内联风格

 <p ng-style="customStyle.style">I should be either green or blue!</p>
Run Code Online (Sandbox Code Playgroud)

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

$scope.turnBlue = function() {
    $scope.customStyle.style = {"color":"blue"};
}
Run Code Online (Sandbox Code Playgroud)

  • 我建议将$ scope.colorClass更改为$ scope.data.colorClass,以避免在更复杂的场景中出现原型问题.我的例子与你的相似:http://jsbin.com/eLOvocu/1/ (3认同)
  • 因此,在解析原始属性时,不会参考原型链的总结,因此您应该使用对象作为属性,以便不会遮蔽属性. (2认同)