这可能是一个简单的问题,但很难搜索......
我根据某些条件改变按钮上的文字:
<button>{{buttonText()}}</button>
<script>
$scope.buttonText = function() {
if (condition) {
return "Here is {{otherVar}}";
} else {
return "Nope!";
}
}
</script>
当然按钮显示&#34;这里是{{otherVar}}&#34;无需将otherVar
解析为表达式。有没有办法让角度评估js字符串?
整个字符串从CMS传递,所以我不能return "Here is" + otherVar;
我正在寻找return angularEval("Here is {{otherVar}}");
答案 0 :(得分: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/ $ interpolate
更简单的解决方案是将condition
和otherVar
放在范围和
<button>{{ condition ? 'Here is ' + otherVar : 'Nope!'}}</button>
答案 1 :(得分:-1)
Claies所说的是有道理的:
VanillaJS来救援!角度表达式仅在控制器中具有绑定到
的上下文
return "Here is {{otherVar}}".replace('{{otherVar}}',otherVar);
答案 2 :(得分:-1)
<script>
$scope.otherVar = "something else";
$scope.buttonText = function (condition) {
if (condition) {
return "Here is " + $scope.otherVar;
} else {
return "Nope!";
}
};