Javascript AngularJS:将变量从控制器传递到要插值的指令

Javascript AngularJS:将变量从控制器传递到要插值的指令,javascript,angularjs,Javascript,Angularjs,我试图将控制器的变量传递到指令中,以便将其放置在指令的模板中 我有这样的指示: app.directive('alert', function() { return { restrict: "E", replace: true, transclude: true, templateUrl: "partials/templates/alert.html", link: function(scope, element, attrs) { sco

我试图将控制器的变量传递到指令中,以便将其放置在指令的模板中

我有这样的指示:

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;
    }
};
});
使用这样的模板:

<div class="alert alert-{{type}}">
    <strong ng-if="type">{{type | capitalize}}:</strong> <span ng-transclude></span>
</div>
$scope.alert = {
    type: 'success',
    message: 'alert message'
}
问题是指令中的
scope.type
在模板中一直显示为字符串“{alert.type}”,而我希望它显示为字符串“success”

我试着给指令一个独立的作用域,比如:

scope: {
    type: '@'
}
但是html中的
ng show=“alert.message
会失败(如果存在,则不会返回true,因此该指令永远不会显示),因为该指令无法访问ctrl的作用域


将此变量从控制器传递到指令并对其进行插值的正确方法是什么?

一个plunkr或fiddle会有所帮助。在没有隔离作用域的情况下也应该可以工作。我建议您将ng show移到指令html标记之外,对于type属性,使用表达式而不使用
{{}
。类似这样的东西

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

{{alert.message}

然后使用隔离作用域方法。

在这种情况下是否需要把手{{…}?请尝试传递
警报。键入
而不传递它们。尝试而不传递则无法修复。我的理解是,指令将其属性作为字符串处理,除非您为指令分配隔离作用域和正确的值(=、@,或&).So
scope.type=attrs.type
不会运行任何计算(除非您使用$parse执行某些操作)。因此您必须使用{{…}对其进行计算,在指令得到它之前。你是对的,这似乎是一个应该可以毫无问题地工作的东西,我组装了一个JSFIDLE:它按照我最初的希望工作。出于某种原因,我的angularjs项目没有这样做。看起来我的问题在其他地方。完全不知道为什么会这样,但在我的实际项目中,我使用的是
templateUrl:'path/to/template.html'
与上面的
模板相反,当我将实际项目从
templateUrl
切换到
template
时,它工作了。你知道为什么会这样吗?
<span ng-show="alert.message">
 <alert type="alert.type">{{alert.message}}</alert>
</span>