从输入更改背景颜色

时间:2015-06-28 03:33:49

标签: javascript html css angularjs

我正在使用棱角分明。我的输入看起来像:

Preferences

基本上当这个改变时,我想要改变div的背景颜色。

我的控制器有一些看起来像这样的行:

<input class="form-control" type="text" ng-model="newBook.color">

然后我要改变div:

$scope.newBook = {};
$scope.newBook.color = "";

$scope.color = ->
  return "background-color: " + $scope.newBook.color;

但是,我收到错误:<div ng-style="{{color()}}"></div>

2 个答案:

答案 0 :(得分:1)

我在这里为你做了一个例子:https://jsfiddle.net/chelogui/2h3hrj1x/

HTML:

<div ng-app="appTest">
    <div ng-controller="contr as controller">
        <input class="form-control" type="text" ng-model="controller.color" />
        <div id="divTest" style="background-color: {{ controller.color }}"></div> 
    </div> 
</div>

Javascript:

angular.module('appTest', [])
    .controller('contr', [function () {
    var self = this;
    self.color = "red";
}]);

Css例证:

#divTest {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin-top: 10px;
}

答案 1 :(得分:1)

这是一个有效的example

您需要更改color功能才能执行此操作:

angular.module('myApp',[])
   .controller('myFirst',['$scope',function($scope){
      $scope.newBook = {};
      $scope.newBook.color = "red";
      $scope.color = function(){
        return "{'background-color' : '"+$scope.newBook.color+"'}";
      }
}])

检查一下:

angular.module('myApp',[])
.controller('myFirst',['$scope',function($scope){
    $scope.newBook = {};
    $scope.newBook.color = "red";
    $scope.color = function(){
        return "{'background-color' : '"+$scope.newBook.color+"'}";
    }
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div ng-app="myApp">
    <div  ng-controller="myFirst" ng-style="{{color()}}">Ajay</div></div>