7

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use & to create a one-way binding, since = is two-way. Just change = to &, and the template to contain {{type()}} and {{message()}}. This is useful if you want to prevent changes to the parent scope, or you want to be able to supply the directive with functions in addition to values.
0

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

1 Comment

Yea but how do i send it to the template as part of the property alert type? i need to do the alert type to be dynamic, tried setting the template from the link and didn't work :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.