将带单引号的动态值作为 ng-true-value 表达式传递失败

2023-12-14

我的复选框输入根据变量动态设置“true”值trueVal,这是一个字符串。

<input ng-model="foo" ng-true-value="'{{trueVal}}'">

例如,对于trueVal = "something", foo === "something"当复选框被选中时。

这有效,除了以下情况:trueVal等于其中包含单引号的字符串:Customer didn't understand。在这种情况下,出现错误:

错误:[$parse:lexerr] Lexer 错误:表达式 ['客户不理解'] 中第 27-28 列 ['] 处的引号未终止。

我无法去掉单引号,因为字符串应按原样设置为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'用于评估,由于单引号未终止,因此格式错误。

简单(但有点难看)的方法是替换' 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".

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将带单引号的动态值作为 ng-true-value 表达式传递失败 的相关文章

随机推荐