Reputation: 25062
I am trying to highlight a row in Angular. Here is my html:
<tr ng-class="{selected: $index==selectedIndex}" ng-repeat="encounter in encounters | filter:search" data-id="{{encounter.id}}" ng-click="getSelectedRow($index)">
Here is the directive that for the row. It has the click handler 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 });
};
}
};
});
This get broadcast to the controller to highlight the row. Here is where the controller should do it's magic:
$scope.$on('selectedRow', function(event, data) {
$scope.selectedIndex = data.rowIndex;
$scope.selectedEncounter = $scope.encounters[data.rowIndex];
});
The code in the controller gets hit, but the row never gets highlighted. What am I missing?
Upvotes: 0
Views: 137
Reputation: 15931
It depends who holds the member property selectedIndex
- if it's the directive, then you shouldn't need $parent, b/c the ng-repeat can see the directive's scope. However, if it's the page controller (or a controller that is housing the directive), then, you need to access it via the directive's $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) {}
Upvotes: 0
Reputation: 7719
ng-class="{selected: $index==$parent.selectedIndex}"
$parent being the key, else you are pointing to the selectedindex on the row, not the scope
Upvotes: 2