iiminov
iiminov

Reputation: 979

Dynamically changing directive attributes in AngularJs

Need a bit of help to get this to finished it off. But if someone has a better suggestion I am an open minded individual.

Basically I've written a directive to swap out templates based on directive attribute.

<div id="popup" class="popup my-directive" type="player" style="display: none;"></div>

Problem that I have is changing the type attribute such that it would trigger $digest and re-evaluate my directive.

$scope.selectTeam = function () {
    $scope.type = 'team';
    //$scope.$apply(function () {
    // bind directive
    $(".popup").attr("type", "team");
    // show popup div
    $(".popup").show();
    //});
};

The purpose of type attribute is to track which template will be bound to popup div.

app.directive('myDirective', function () {
    return {
        restrict: 'AEC', // Attribute, Element, Class
        transclude: true, // expose controller scope
        templateUrl: function(element, attr){
            var type = typeof attr.type !== 'undefined' ? attr.type : 'player';

            if(!type) return;

            return 'search-' + type + '-tpl.html';
        },
    }
});

For live example please have a look at my plunker.

I will now try something with $compile to build my popup with new type value in each select function but really don't fancy this approach.

update

OK, I have cracked it quicker than originally expected. Live plunker.

Changes I introduced to controller:

$scope.selectTeam = function () {
    $scope.type = 'team'; // trigers $digest
    $(".popup").replaceWith($compile(angular.element(document).find("my-directive").attr("type", "team"))($scope));
    $(".popup").show();
};

Changes I introduced to HTML:

<my-directive id="popup" class="popup" type="player" style="display: none;"></my-directive>

The only issue this present that I noticed is Cannot read property 'insertBefore' of null when I try to search. But I can live with this.

As I mentioned before if someone has a different idea/approach or noticed something funny in my code please do share.

Upvotes: 0

Views: 1679

Answers (1)

Okazari
Okazari

Reputation: 4597

After a talk i found out two solutions.

First you can do what you need using ng-include this way instead of creating a custom directive (see it working into this plunker) :

<div ng-show="showSelect" ng-include="'search-'+type+'-tpl.html'">

Secondly i pointed out that this could be a modal using $modal (using "templateUrl") from ui-boostrap.

I actually tend to prefer the second option as you can define a controller, template, css etc... for each modal which is a bit cleaner and readable.

Upvotes: 1

Related Questions