Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 629
msqar Avatar asked Dec 11 '13 20:12

msqar


People also ask

Which of the following is not an AngularJS directive?

ng-state is not an AngularJS directive. Q 15 - Which of the following is true about ng-app directive? A - ng-app directive defines and links an AngularJS application to HTML. B - ng-app directive indicates the start of the application.

What are the attributes that can be used during the creation of a new AngularJS directives?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Which directive is used to assign values to the variables in AngularJS?

ng-init directive It is used to declare and assign values to the variables for an AngularJS application.


1 Answers

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

like image 104
Maxim Shoustin Avatar answered Sep 29 '22 10:09

Maxim Shoustin