如何基于$ scope将CSS样式应用于指令内的ng-repeat元素。$ watch on it属性?

时间:2014-02-12 08:18:42

标签: javascript html css angularjs

我的观看代码:

<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样式应用于当前元素。在指令 中实现 的“角度方式”是什么?

2 个答案:

答案 0 :(得分:2)

您不必在示例中更改指令中的样式。你可以简单地做一些事情:

<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放在指令视图中。这样,您可以轻松地操作它。

答案 1 :(得分:0)

在指令中,您可以使用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