我正在构建一个应用程序。我的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模板是由unittable控制器加载的。
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是一个service data从rest获取数据,但在这里不需要关注。
我需要根据单元格中的值条件设置表单元格的类。我不想使用现有的表格/网格工具,这是一个非常简单的表格使用工具。是否有什么我做错了,或者有更好的方法来获得基于其值的单元格类?
可能是被调用的方法的作用域有问题。
请建议。
像这样将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>
恰好
使用getCellColor(col)代替getCellColor({{col}})
ng-class使用$scope.$eval()对表达式求值。你不需要使用一对括号
更新:虽然你可以使用getCellColor(col)方法来改变类。它只能求一次值。建议为每个col.