如何在Angular Directive Scope中设置默认值?

kob*_*490 6 angularjs angularjs-directive angularjs-scope

-在角度,我有以下情形,其中一个指令可以接受哪些应该默认为一个可选的布尔参数,真正在默认情况下,只要不指定.

例:

<my-directive data-allow-something="false">
    ... this works as expected as no default value should be set in this case ...
</my-directive>

<my-directive>
    ... but in this case i'd like allowSomething to equal true  ...
</my-directive>
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法,但由于某种原因,真正的价值并没有坚持allowSomething.把它变成'=?' 可选的双向绑定既不起作用,因为我传递的值应该是具体的true/false而不是字段引用.

angular.module('myApp').directive('myDirective') {
    ...
    controller: function($scope){
        if (!$scope.allowSomething)
            $scope.allowSomething = true;
    },
    ....
    scope: function(){
        allowSomething: '@'
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我确信应该有一个简单的方法来实现这一点,所以我缺少什么?

以下 故障单中给出的解决方案:具有默认选项的Angular指令不足以满足我的需要,因为$ compile函数将阻止链接功能起作用.另外,传入的布尔值不是引用类型,我不能给它一个双向绑定.

Mic*_*ely 19

我认为检查该值的更好方法是查找未定义的值,如下所示:

controller: function($scope){
    if (angular.isUndefined($scope.allowSomething))
        $scope.allowSomething = true;
}
Run Code Online (Sandbox Code Playgroud)

我曾经遇到过同样的问题,这对我有用.我认为最好的方法是使用angular的方法处理事物.