简短版本, ng-true-val
需要一个常量,并且将以下表达式作为参数传递:'Customer didn't understand'
用于评估,由于单引号未终止,因此格式错误。
简单(但有点难看)的方法是替换'
with \'
在视图中(这不会改变实际值 - 只是对其进行编码):
<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
calls $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"
.