2014-05-19 22 views
0

我有一个指令,在其模板中有ng-class的用法。当我尝试添加ng-class父“使用率”的元素,它炸毁说:Directive中的AngularJS ng-class用法

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 
       }); 
      }; 
     } 
    }; 
}); 

回答

1

我相信原因是占位符,并在模板中指定ng-class两的replace: true指令。 Angular将用指令的模板替换<div ng-table-row>,并将从<div ng-table-row>应用到模板的根元素,该元素也具有ng-class指令。这些可能会混淆并导致问题。

在你的情况下,溶液可以是如在link()手动应用CSS类一样简单:(假设当然selectedRowrow处于scope

scope.$watch(
    function() { 
     return scope.selectedRow && scope.selectedRow.id === scope.row.id; 
    }, 
    function(newval) { 
     elem.toggleClass("ng-table-selected", newval); 
    } 
); 

+0

啊,我想通这就是它被炸毁的原因。只是不确定最好的处理方式。谢谢,我会试一试。 – amcdnl

+0

顺便说一下,这个问题的演示小提示在这里:http://jsfiddle.net/k2GrW/它的工作原理,但是当你激活'ng-class'('xxxng-class' - >'ng-类在模板的根元素中)它给出了相同的错误。 –