我有我的复选框输入,它根据变量动态设置"true"值,该变量trueVal是一个字符串.
<input ng-model="foo" ng-true-value="'{{trueVal}}'">
Run Code Online (Sandbox Code Playgroud)
例如,对于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>
Run Code Online (Sandbox Code Playgroud)
所以,给定:
options = {
0: {trueVal: "Customer was late"},
1: {trueVal: "Customer didn't understand"}
};
Run Code Online (Sandbox Code Playgroud)
我希望看到:
foo = {
1: "Customer didn't understand"
};
Run Code Online (Sandbox Code Playgroud)
如果选中第二个框.
短版本,ng-true-val期望一个常量,并将以下表达式作为参数传递:'Customer didn't understand'用于评估,由于未终止的单引号而导致格式错误.
简单(但有点丑陋)的方法是,以取代'与\'在视图(这并不改变实际值-只是对其进行编码):
<input type="checkbox" ng-model="foo"
ng-true-value="'{{trueVal.replace('\'', '\\\'')}}'"
ng-false-value="null">
Run Code Online (Sandbox Code Playgroud)
更好的方法可能是使用ng-change:
<input type="checkbox" ng-model="t"
ng-change="foo = t ? trueVal : null">
Run Code Online (Sandbox Code Playgroud)
更长的版本
在封面下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
Run Code Online (Sandbox Code Playgroud)
在您的情况下,您需要获取变量trueVal,将其插值为值{{trueVal}},以成为'{{trueVal}}'最终将按上述方式进行求值的表达式的一部分.
这就是为什么替换'作品\',因为它逃脱了单打引号,好像你直接写了表达式:
ng-true-value="'Customer didn\'t understand'"
Run Code Online (Sandbox Code Playgroud)
如果您确定"您的值中没有双引号()options,您也可以简单地反转引号的顺序,而无需执行以下操作replace:
ng-true-value='"{{trueVal}}"`
Run Code Online (Sandbox Code Playgroud)
当然,如果trueVal价值有双引号,这将失败的原因相同:something with "quotes".
| 归档时间: |
|
| 查看次数: |
8566 次 |
| 最近记录: |