【问题标题】:How can I apply a CSS style to an ng-repeat element inside a directive, based on $scope.$watch on it's attribute?如何根据 $scope.$watch 的属性将 CSS 样式应用于指令内的 ng-repeat 元素?
【发布时间】:2014-03-10 10:38:13
【问题描述】:

我的查看代码:

<div ng-repeat = "i in items track by $index">
   <myDirective label = "i.labels"> </myDirective>
</div>

部分指令代码:

return {
  scope : {
    label : '='
  }
  link : function($scope, elem, attrs){
     $scope.$watch('label', function(v){
        if(v[1] == "somevalue"){ // apply a css style to this ng-repeat item.}
     });
  }

}

我想根据v[1] 将css 样式应用于当前元素。 在指令中实现这一目标的“角度方式”是什么?

【问题讨论】:

标签: javascript html css angularjs


【解决方案1】:

您不必在示例中的指令中更改样式。您可以简单地执行以下操作:

<div ng-repeat="i in items track by $index" 
     ng-style="{ background: i.labels[1] == 'somevalue' ? 'red' : 'blue' }">
   <myDirective label="i.labels"></myDirective>
</div>

但是如果你真的想改变指令的样式,那么我认为你应该把外部的 div 放在指令的视图中。这样,您就可以轻松操作它。

【讨论】:

  • 角度表达式是否支持三元运算?
  • 他们没有,你必须这样做 i.labels[1] == 'somevalue' && 'red' || “蓝色”
  • 他们从 Angular 1.1.5 开始就这样做了。
  • @AlonGubkin,我知道这种技术。我的问题是针对角度指令的。永远感谢。
【解决方案2】:

在指令中,您可以使用 jqLite 选择器来查找父级 ng-repeat div。然后,如果满足所需条件,您可以应用特定的类。

我创建了以下示例应用程序。

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [{
    labels: ["red", "black"]
  }, {
    labels: ["faint-green", "green"]
  }, {
    labels: ["pink", "orange"]
  }, {
    labels: ["USA"]
  }];
}).directive('mydirective', function() {
  return {
    restrict: 'AE',
    scope: {
      label: '='
    },

    link: function($scope, elem, attrs) {
      $scope.repeatingElem = $(elem).parent('div[ng-repeat]');
      $scope.$watch('label', function(v) {

        if (v[1] == "green") {
          // apply a css class to ng-repeat element.
          $scope.repeatingElem.addClass('bg-success');
        }

      });
    }
  }
});

index.html

<!doctype html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <link rel="stylesheet" href="style.css">
  <script>
    document.write("<base href=\"" + document.location + "\" />");
  </script>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">

  <div ng-repeat="i in items">
    <mydirective label="i.labels"></mydirective> {{i.labels}}
  </div>

</body>

</html>

Plnkr Sample

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2011-01-20
    • 2020-06-08
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多