Thursday, 12 September 2013

Trying to reuse directive with mutable $scope through $compile, but it's appending content

Trying to reuse directive with mutable $scope through $compile, but it's
appending content

I got two directives that depend on each other, to create a "Google
Images" kind effect (that expand with info below the clicked image):
Produtos.directive('produtosList', ['$timeout', '$compile', function
($timeout, $compile){
var $info = angular.element('<div class="produtos-info"></div>');
return {
restrict: 'A',
template:
'<li class="produtos-pad" ng-repeat="item in filtered">' +
'<div class="produtos-list-item">' +
'</div>' +
'</li>',
link : function ($scope, element){
var info = $compile($info);
element.on('click', '.produtos-pad', function (e){
var
$this = $(e.currentTarget),
scope = $this.scope();
$this.toggleClass('produtos-list-item-active');
$this.append($info); // works and the element get's reused,
without the need to detach()
scope.$apply(function(){
info(scope.$scope); // scope.$scope actually comes from the
produtosListItem directive $scope
});
});
}
};
}]);
Produtos.directive('produtosInfo', [function (){
return {
restrict : 'C',
templateUrl: '/produtos/template/produtosInfo',
replace: true,
scope: true,
compile: function(tElement){
var
$arrow = tElement.find('.produtos-zoom-arrow');
return function ($scope, element){
$scope.$on('info', function(ev, scope){
var
p = scope.element.parent(),
po = p.position();
element.css({
top: po.top + p.outerHeight(true)
});
$arrow.css({
left: po.left + (p.width() / 2)
});
});
};
}
};
}]);
produtosInfo template HTML is:
<div class="produtos-zoom" ng-switch="scope">
<div class="produtos-zoom-arrow"></div>
<div ng-switch-when="oem">
{{ nome }}
</div>
<div ng-switch-when="reposicao">
</div>
</div>
The new scope get's applied to the $compiled element, BUT, everytime I
change items (for example, I click item 1, then click item 2), the
ng-switch statement inside the element get's appended. Its creating a new
scope inside the ng-switch-when everytime I call info(scope) why is that?
Below is an example of the HTML inside my reusable element after the
second click:
<div ng-switch="scope" class="produtos-info produtos-zoom ng-scope">
<div class="produtos-zoom-arrow"></div>
<!-- ngSwitchWhen: oem -->
<!-- ngSwitchWhen: reposicao -->
<div ng-switch-when="oem" class="ng-scope ng-binding">
Diafragmas para sistemas de freio a ar
</div><div ng-switch-when="oem" class="ng-scope ng-binding">
Coifas para semieixos homocinéticos (CVJ)
</div>
</div>
each ng-scope ng-binding has their own scope, how can I tell angular to
"clean" it after the scope has changed? Is it a bug with ng-switch?

No comments:

Post a Comment