我想在Angular中突出显示一行。这是我的HTML:
<tr ng-class="{selected: $index==selectedIndex}" ng-repeat="encounter in encounters | filter:search" data-id="{{encounter.id}}" ng-click="getSelectedRow($index)">
这是该行的指令。它有点击处理程序getSelectedRow()
angular.module('app').directive('encounterItemTable', function ($rootScope) {
return {
restrict: 'A',
replace: true,
templateUrl: 'views/encounter.item.table.html',
scope: {
encounters : '='
},
link: function(scope) {
scope.getSelectedRow = function(index) {
$rootScope.$broadcast('selectedRow', { rowIndex: index });
};
}
};
});
这将广播到控制器以突出显示该行。这是控制器应该做的魔术:
$scope.$on('selectedRow', function(event, data) {
$scope.selectedIndex = data.rowIndex;
$scope.selectedEncounter = $scope.encounters[data.rowIndex];
});
控制器中的代码被命中,但该行永远不会突出显示。我错过了什么?
答案 0 :(得分:2)
ng-class =“{selected:$ index == $ parent.selectedIndex}”
$ parent是键,否则你指向行上的selectedindex而不是范围
答案 1 :(得分:0)
这取决于谁持有成员属性selectedIndex
- 如果它是指令,那么你不应该需要$ parent,b / c ng-repeat可以看到指令的范围。但是,如果它是页面控制器(或容纳指令的控制器),那么,您需要通过指令的$ parent访问它。
jsfiddle:http://jsfiddle.net/4HWbe/9/
HTML
<div ng-controller="MyCtrl">enter a number from 0 - 9
<input ng-model='selectedIndex' type='text'>
Uses appliction scope
<ul>
<li ng-repeat='x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' ng-class='{"selected": $index==selectedIndex}'>{{x}}</li>
</ul>
<my-directive></my-directive>
</div>
SCRIPT
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function () {
return {
restrict: 'E',
template: "<div><hr/>Uses $parent.scope<ul><li ng-repeat='y in [10, 11, 12, 13, 14, 15, 16, 17, 18, 10]' ng-class='{\"selected\": $index==$parent.selectedIndex}'>{{y}}</li></ul></div>"
};
});
function MyCtrl($scope) {}