【问题标题】:Angularjs Scope method not being called by ng-classng-class没有调用Angularjs Scope方法
【发布时间】:2014-06-11 00:07:26
【问题描述】:

我正在构建一个应用程序。 我的 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()};
});

请注意,ma​​inController 是父控制器。 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>

现在指令正在以它应该的形式打印正确的数据,但是没有调用父 ma​​inController 中的 getCellColor() 方法。 p>

unitData 是服务数据获取数据过休息,但这里不关心。

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

也许被调用的方法的范围有问题。

请提出建议。

【问题讨论】:

  • 试试ng-class="getCellColor(col)"?
  • thnx David.. 但它仍然没有在控制器中被调用。

标签: javascript angularjs ng-class


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 感谢您指出这一点。但是仍然没有调用 ng-class 方法。
    猜你喜欢
    • 2013-04-03
    • 2015-04-25
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-10-03
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多