2016-07-20 56 views
0

这可能是一个简单的问题,但很难查找...评估在Javascript中的字符串表达式角

我有一个按钮上的文字改变基于一些条件:

<button>{{buttonText()}}</button> 
<script> 
    $scope.buttonText = function() { 
     if (condition) { 
      return "Here is {{otherVar}}"; 
     } else { 
      return "Nope!"; 
     } 
    } 
</script> 

当然该按钮会显示“Here is {{otherVar}}”,而不会将otherVar解析到表达式中。有没有一种方法来角度评估js字符串?

整个字符串被从CMS过去了,所以我不能只是做return "Here is" + otherVar;我正在寻找类似return angularEval("Here is {{otherVar}}");

+2

瓦你不能在JS中的字符串中添加实际的'otherVar'而不是使用类似angularEval的东西? –

+1

你不能用这种方式评估表达式;角表达式在控制器中只有上下文绑定的上下文(它们的具体'$ scope'实例)。将表达式保存到数据库没有任何意义,因为没有办法知道该表达式将在相同的控制器上进行评估,并且定义了相同的变量。 – Claies

+0

我明白了。该字符串保存在数据库中,以便客户端可以在CMS中对其进行翻译:对于英语,“这是{{otherVar}}”,对德语是“Hier ist {{otherVar}}”。 – Keith

回答

1
<button>{{buttonText()}}</button> 
<script> 
    //controller injects $interpolate like app.controller($scope, $interpolate) 
    $scope.buttonText = function() { 
     if (condition) { 
      var dataObj = { otherVar : 'bla' }; //can be scope 
      var exp = $interpolate('Here is {{otherVar}}'); 
      return exp(dataObj); 
     } else { 
      return "Nope!"; 
     } 
    } 
</script> 

阅读更多:https://docs.angularjs.org/api/ng/service/ $插值

也是简单的解决方法是把在范围conditionotherVar

<button>{{ condition ? 'Here is ' + otherVar : 'Nope!'}}</button> 
+0

我认为我的解决方案对我来说比较好,但是您完全可以回答更一般的问题。即使我没有使用它,我仍然是最好的。希望它能帮助别人。 – Keith

+0

你的解决方案使用简单的JS,也可以只是“Here is”+ otherObj,thx for the vote btw – bresleveloper

+0

是的,但在某些翻译中,otherVar是在字符串中间的某处。 – Keith

-1

什么Claies说的很有道理:

角度表达只有内语境他们绑定的控制器

VanillaJS救援!

return "Here is {{otherVar}}".replace('{{otherVar}}',otherVar); 
-1
<script> 
$scope.otherVar = "something else"; 
$scope.buttonText = function (condition) { 
    if (condition) { 
     return "Here is " + $scope.otherVar; 
    } else { 
     return "Nope!"; 
    } 
}; 

+0

你能解释这是如何帮助的(也许只是一两句话)。只是抛出一些代码不被认为是一个很好的答案。 – litelite