我正在构建一个应用程序。 我的 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'
};
});
我的 Controller 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 是父 Controller 。 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是service data get data over 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>
关于javascript - ng-class 未调用 Angularjs Scope 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24152770/