我有我的复选框输入,它根据变量 trueVal
动态设置“真”值,这是一个字符串。
<input ng-model="foo" ng-true-value="'{{trueVal}}'">
例如,对于
trueVal = "something"
, foo === "something"
当复选框被选中时。这有效,除非
trueVal
等于一个带单引号的字符串:Customer didn't understand
.在这种情况下,会出现错误:Error: [$parse:lexerr] Lexer Error: Unterminated quote at columns 27-28 ['] in expression ['Customer didn't understand'].
我不能去掉单引号,因为字符串应该按原样设置为
foo
.更广泛的背景:
我正在根据
options
列表创建一组复选框我从后端得到的:<div ng-repeat="(key,option) in options">
<input type="checkbox"
ng-model="foo[key]"
ng-true-value="'{{option.trueVal}}'"
ng-false-value="null">
</div>
所以,给定:
options = {
0: {trueVal: "Customer was late"},
1: {trueVal: "Customer didn't understand"}
};
我希望看到:
foo = {
1: "Customer didn't understand"
};
如果第二个框被选中。
最佳答案
短版 , ng-true-val
需要一个常量,并且将以下表达式作为参数传递:'Customer didn't understand'
用于评估,由于未终止的单引号而格式错误。
简单(但有点难看)的方法是替换 '
与 \'
在 View 中(这不会改变实际值 - 只是对其进行编码):
<input type="checkbox" ng-model="foo"
ng-true-value="'{{trueVal.replace('\'', '\\\'')}}'"
ng-false-value="null">
更好的方法可能是使用
ng-change
:<input type="checkbox" ng-model="t"
ng-change="foo = t ? trueVal : null">
加长版
幕后
ng-true-value
电话$parse
服务:var parseFn = $parse(expression)
,并期待 parseFn.constant === true
.后者仅在表达式为常量时才成立:expression = 'string'; // string literal
expression = '5' // number literal
expression = {v: 'string'} // object literal with a constant
expression = 'foo' + 'bar'; // expression that evaluates to a constant
在您的情况下,您需要采用变量
trueVal
,将其插入到值 {{trueVal}}
, 成为表达式的一部分 '{{trueVal}}'
最终将按照上述说明进行评估。这就是为什么要替换
'
工作到 \'
,因为它转义了单引号,就像您直接编写了表达式一样:ng-true-value="'Customer didn\'t understand'"
如果您确定在
"
的值中没有双引号( options
) ,您也可以简单地颠倒引号的顺序,而无需执行 replace
:ng-true-value='"{{trueVal}}"`
如果
trueVal
,这当然会出于同样的原因而失败。值有双引号:something with "quotes"
.
关于angularjs - 将带有单引号的动态值作为 ng-true-value 表达式传递失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29006996/