如何在 AngularJS 指令范围中设置默认值? [英] How to set a default value in an AngularJS Directive Scope?

查看:33
本文介绍了如何在 AngularJS 指令范围中设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 AngularJS 中,我有以下场景,指令可以接受可选的布尔参数,默认情况下该参数应默认为 true只要未指定.>

示例:

...这按预期工作,因为在这种情况下不应设置默认值...</my-directive><我的指令>...但在这种情况下,我希望 allowSomething 等于 true ...</my-directive>

我已经尝试了以下方法,但由于某种原因,true 值不会坚持 allowSomething.使它成为 '=?'可选的双向绑定 也不起作用,因为我传递的值应该是具体的真/假而不是字段引用.

angular.module('myApp').directive('myDirective') {...控制器:功能($范围){如果 (!$scope.allowSomething)$scope.allowSomething = true;},....范围:函数(){允许某事:'@'}...}

我确定应该有一个简单的方法来实现这一点,那么我错过了什么?

以下票证中给出的解决方案:AngularJS 指令与默认选项不足以满足我的需求,因为 $compile 函数会阻止链接函数工作.另外,传入的布尔值不是引用类型,我不能给它双向绑定.

解决方案

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

控制器:函数($scope){如果 (angular.isUndefined($scope.allowSomething))$scope.allowSomething = true;}

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

In AngularJS, I have the following scenario where a directive can accept an optional boolean parameter which should default to true by default, whenever it is not specified.

Example:

<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>

I've tried the following approach, but for some reason the true value doesn't stick on allowSomething. making it a '=?' optional two way binding doesn't work neither as my passed value should be a concrete true/false and not a field reference.

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

I'm sure there should be a simple way to achieve this, so what am i missing?

The solutions given at the following ticket: AngularJS directive with default options are not sufficient for my needs since the $compile function will prevent the link function from working. plus, the passed-in boolean value is not a reference type and i cannot give it a two-way binding.

解决方案

I think a better way to check that value is look for an undefined value like this:

controller: function($scope){
    if (angular.isUndefined($scope.allowSomething))
        $scope.allowSomething = true;
}

I had the same issue once and this worked for me. I think the best method is to use angular's methods for handling things.

这篇关于如何在 AngularJS 指令范围中设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆