2016-07-20 59 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