Javascript Angular指令设置div的背景色

Javascript Angular指令设置div的背景色,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,假设我有一个div元素: <div id="wrapper"> some text </div> 一些文本 如何编写角度指令,使背景取决于输入 例如,我尝试: <div id="wrapper" color temperature="51"> some text </div> 一些文本 根据指令: .directive('color', function() { return { restrict: 'A',

假设我有一个div元素:

<div id="wrapper">
   some text
</div>

一些文本
如何编写角度指令,使背景取决于输入

例如,我尝试:

<div id="wrapper" color temperature="51">
   some text
</div>

一些文本
根据指令:

.directive('color', function() {
  return {
    restrict: 'A',
    replace: true,
    scope: {
      temperature: '='
    },
    template: '<div ng-class="temperatureCSS">Test</div>',
    link: function($scope) {

      $scope.$watch('temperature', function(v) {
        if(!v) { return; }

        var temperature = v;
        console.log("temperature", v)

        if(temperature > 31) {
          $scope.temperatureCSS = "redCSS" // redCSS works and is defined
        }

      });
    }
  }
})
指令('color',function()){ 返回{ 限制:“A”, 替换:正确, 范围:{ 温度:'=' }, 模板:“测试”, 链接:功能($scope){ $scope.$watch('温度'),功能(v){ 如果(!v){return;} var温度=v; 控制台日志(“温度”,v) 如果(温度>31){ $scope.temperatureCSS=“redCSS”//redCSS工作并已定义 } }); } } })
但这并不完全有效。我认为这个问题在模板中的某个地方

你应该检查一下角度。看起来部分问题在于您试图使用属性指令插入模板。如果要插入模板,则需要指定元素指令。

请详细解释您面临的问题。因为我从您上面提供的代码中了解到的是,假设您有一个输入字段,每当您更改该字段中的值时,背景应根据$watch函数中的条件进行更改

因此,如果是这种情况,我们假设控制器的代码如下:

.controller('Main', function($scope){

  $scope.myInputValue = 20;

})
<input ng-model="myInputValue" />
使用ngModel指令将输入字段绑定到scope属性myInputValue,如下所示:

.controller('Main', function($scope){

  $scope.myInputValue = 20;

})
<input ng-model="myInputValue" />

现在您要做的就是在指令中使用属性

<div id="wrapper" color temperature="myInputValue">
  some text
</div>

一些文本
就这样

也许能帮你。