0

I'm trying to pass a controller's variable into a directive so it can be placed in the directive's template.

I have a directive like so:

app.directive('alert', function() {
return {
    restrict: "E",
    replace: true,
    transclude: true,
    templateUrl: "partials/templates/alert.html",
    link: function(scope, element, attrs) {
        scope.type = attrs.type;
    }
};
});

with a template like this:

<div class="alert alert-{{type}}">
    <strong ng-if="type">{{type | capitalize}}:</strong> <span ng-transclude></span>
</div>

And I use the directive as follows:

 <alert ng-show="alert.message" type="{{alert.type}}">{{alert.message}}</alert>

My ctrl has a variable that looks like this:

$scope.alert = {
    type: 'success',
    message: 'alert message'
}

The problem is that scope.type in the directive keeps showing up as the string '{{alert.type}}' in the template, when I want it to show up as simply the string 'success'.

I've tried giving the directive an isolate scope like:

scope: {
    type: '@'
}

but then the ng-show="alert.message in the html fails (won't return true if it exists, so the directive is never displayed) because the directive lost access to the ctrl's scope.

What's the proper way of passing this variable off from the controller to the directive and having it interpolated?

4

1 に答える 1

0

plunkr または fiddle が役に立ちました。孤立したスコープがなくても機能するはずです。私が提案できるのは、 ng-show をディレクティブ html タグの外に移動し、 type 属性には なしで式を使用すること{{}}です。このようなもの

<span ng-show="alert.message">
 <alert type="alert.type">{{alert.message}}</alert>
</span>

次に、分離スコープ アプローチを使用します。

于 2013-07-09T03:58:54.963 に答える