Angularjs Scope方法不被ng-class调用

时间:2014-06-11 00:07:27

标签: javascript angularjs ng-class

我正在构建一个应用程序。 我的index.html看起来像:

<html ng-app='myApp'>
 <body ng-controller='mainController'>
   <div ng-view>
   </div>
 </body>
</html>

我的主模块js看起来像是:

var myApp = angular.module('myApp',['ngRoute','mycontrollers']);

myApp.directive('countTable', function(){
  return {
    restrict: 'E',
    scope: {tableType:'=tableType'},
    templateUrl: '../html/table.html'
  };
});

我的控制器JS看起来像:

var mycontrollers = angular.module('mycontrollers',['dataservice']);

mycontrollers.controller('mainController', function ($scope) {

   $scope.getCellColor = function (value) {
        if(value===20){
            return 'sucess';
         }           
         else {
            return 'error';
         }
   };
});

mycontroller.controller('unitTableController', function($scope,unitdata) {
  $scope.something = {data: unitdata.getData()};
});

请注意, mainController 是父控制器。 unitTableController 继承自mainController。

指令 countTable 模板由unitTableController加载。

table.html 如下所示:

 <table>
   <tr ng-repeat="row in tableType.data.rows">
      <td ng-repeat="col in row track by $index" ng-class="getCellColor(col)">{{col}}</td>
   </tr>
 </table>

持有该指令的html如下所示:

<div>
  <count-table table-type='something'></count-table>
</div>

现在该指令正在以预期的形式打印正确的数据,但未调用父 mainController 中的 getCellColor()方法。

unitData 是服务数据获取静态数据,但此处并不重要。

我需要根据单元格中的值条件设置表格单元格的类。 我不想使用现有的表/网格工具,它是一个非常简单的工具使用表。 有什么我做错了,还是有更好的方法来根据其价值获得一个单元格的类?

调用方法的范围可能有问题。

请建议。

2 个答案:

答案 0 :(得分:2)

getCellColor方法传递给指令,如下所示:

<count-table table-type='tableType' 
get-cell-color='getCellColor(col)'>
</count-table>

该指令如下所示:

app.directive('countTable', function(){
  return {
    restrict: 'E',
    scope: {
      tableType:'=tableType',
      getCellColor: '&'
    },
    templateUrl: 'table.html'
  };
});

指令模板如下所示:

 <table>
   <tr ng-repeat="row in tableType.data.rows">
      <td ng-repeat="col in row track by $index" ng-class="getCellColor({col: col})">{{col}}</td>
   </tr>
 </table>

Plunker

答案 1 :(得分:0)

使用getCellColor(col)代替getCellColor({{col}})

ng-class使用$ scope。$ eval()来计算表达式。你不需要使用一对括号

更新: 虽然您可以使用getCellColor(col)方法来更改类。它可以只评估一次。建议为每个col设置属性。