我有一个指令,在其模板中使用ng-class
。当我尝试将ng-class
添加到父'useage'元素时,它会爆炸说:
Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 48 of the expression [{ 'active': $stateParams.recordId === row.id }
{ 'ng-table-selected': selectedRow && selectedRow.id === row.id }] starting at [{ 'ng-table-selected': selectedRow && selectedRow.id === row.id }].
http://errors.angularjs.org/1.2.14/$parse/syntax?
处理这样的事情的正确方法是什么?
父用法html:
<div ng-table-row ng-repeat="row in results"
ng-class="{ 'active': $stateParams.recordId === row.id }"
row-click="rowClick(row)"></div>
指令html:
<div class="ng-table-table-row"
ng-click="rowClicked(row, $event)"
ng-class="{ 'ng-table-selected': selectedRow && selectedRow.id === row.id }"
ng-style="{ height: tableOptions.rowHeight, top: rowTop, width: rowWidth }"
ng-transclude></div>
指令JS:
module.directive('ngTableRow', function ($rootScope) {
return {
restrict: 'AE',
replace: true,
transclude: true,
templateUrl: 'common/components/table/views/row.tpl.html',
link: function ($scope, $element, $attributes) {
$scope.rowTop = $scope.$index * $scope.tableOptions.rowHeight;
$scope.rowClicked = function(row){
// body listener to set active
$scope.bodyRowClicked(row);
// row click public api
$scope.rowClick({
row: row
});
};
}
};
});
答案 0 :(得分:1)
我认为原因是在占位符和ng-class
指令的模板中都指定了replace: true
。 Angular会将<div ng-table-row>
替换为指令的模板,并将ng-class
中的<div ng-table-row>
应用于模板的根元素,该元素也具有ng-class
指令。这些可能会混淆并导致问题。
在您的情况下,解决方案可能就像在link()
中手动应用CSS类一样简单:
scope.$watch(
function() {
return scope.selectedRow && scope.selectedRow.id === scope.row.id;
},
function(newval) {
elem.toggleClass("ng-table-selected", newval);
}
);
(当然假设selectedRow
和row
位于scope
。