我能够将一个class属性传递给angularJS中的指令模板吗?

时间:2021-11-19 15:12:07

I got this directive in angularJS

我在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 个解决方案

#1


4  

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

#2


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.

在链接函数中,您可以执行类似attrs.type和attrs.msg之类的操作来检索传递给指令的值。

#1


4  

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

#2


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.

在链接函数中,您可以执行类似attrs.type和attrs.msg之类的操作来检索传递给指令的值。