msqar
msqar

Reputation: 3040

Am I able to pass a class attribute to a directive template in angularJS?

I got this directive in angularJS

productApp.directive('notification', function($timeout) {
    return {
        restrict : 'E',
        replace : true,
        scope : {
            type: "@",
            message: "@"
        },
        template : '<alert class="alert alert-type">message</alert>',
        link : function(scope, element, attrs) {
            $timeout(function() {
                element.hide();
            }, 3000);
        }
    }
});

So i can call it from the view like this:

<notification type="alert.type" message="alert.msg"></notification>

In the controller i got the alert object defined:

$scope.alert = { type : 'success', msg : 'This is a test'};

How am i able to pass the type dynamically? tried that and it didn't work. If i pass alert-success to the directive, it works, but i want it to be dynamic.

Am i able to pass it dynamically by doing that?

Thanks

Upvotes: 7

Views: 7285

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77920

Try to change directive to this one:

productApp.directive('notification', function($timeout) {
    return {
        restrict : 'E',
        replace : true,
        scope : {
            type: "=",
            message: "="
        },
       template : '<alert class="alert alert-{{type}}">{{message}}</alert>',
        link : function(scope, element, attrs) {
            $timeout(function() {
               // element.hide();
            }, 3000);
        }
    }
});

Since you have isolated scope use = to bind parent scope property

Demo Fiddle

Upvotes: 5

smk
smk

Reputation: 5912

In your link function, you can do something like this attrs.type and attrs.msg to retrieve the value you pass to your directive.

Upvotes: 0

Related Questions