I have an ng-class initialization issue when I move the code which was in my controller, but related to the DOM, to a directive. To be short, here is some code:
view.html
<div ng-repeat="foo in foos" ng-click="rowClick($index)>
<div ng-class="changeOpacity($index)>
<span>{{foo.title}}</span>
<span>{{foo.name}}</span>
<span>{{foo.date}}</span>
...
// some div with hidden content. Show when clicking on the div
</div>
<div>
controller.js
$scope.rowClick = function (idx) {
// unfold the clicked div to show content
};
$scope.changeOpacity = function (idx) {
if (this is the div clicked) {
return {dark: true};
} else {
return {light: true};
}
So when I have a list of div. When I clicked on a div, all the other divs get darker excepts this one.
Everything is working fine when $scope.rowClick and $scope.changeOpacity are in my controller.
When I move rowClick and changeOpcaity to a directive:
myBar.js
myApp.directive('myBar', function () {
...
return {
restrict:'A',
link: function (scope, element) {
element.bind('click', function () {
...
same code from rowClick
...
scope.changeOpacity = function () {
...
same code from changeOpacity
}
scope.$apply();
}
}),
changeOpacity: function () {
...
return {light: true} // for all divs
}
}
});
Now my view.html is something like that:
<div ng-repeat="foo in foos" ng-click="rowClick($index) my-bar>
<div ng-class="changeOpacity($index)>
<span>{{foo.title}}</span>
<span>{{foo.name}}</span>
<span>{{foo.date}}</span>
...
// some div with hidden content. Show when clicking on the div
</div>
<div>
But now the divs are not initialized anymore with the ng-class. I have to click one time on each div to initialize it, with the link function which listen to the click.
How can I initialize the ng-class inside the directive ?
Thanx.