如何在AngularJS指令范围内设置默认值? [英] How to set a default value in an AngularJS Directive Scope?
问题描述
在AngularJS中,我遇到以下情况:指令可以接受可选的布尔参数,默认情况下,未指定时,布尔参数默认为 true .>
示例:
<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>
我已经尝试了以下方法,但是由于某些原因, true 值不会保留在 allowSomething 上.使其成为'=?'可选的双向绑定也不起作用,因为我传递的值应该是具体的true/false而不是字段引用.
angular.module('myApp').directive('myDirective') {
...
controller: function($scope){
if (!$scope.allowSomething)
$scope.allowSomething = true;
},
....
scope: function(){
allowSomething: '@'
}
...
}
我确定应该有一种简单的方法来实现这一目标,那么我想念的是什么?
以下票证上给出的解决方案:带有默认选项的AngularJS指令 不足以满足我的需要,因为$ compile函数将阻止链接函数工作.另外,传入的布尔值不是引用类型,并且我无法对其进行双向绑定.
我认为检查该值的更好方法是查找未定义的值,如下所示:
controller: function($scope){
if (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屋!