[英]$scope variable is treated as string - AngularJs
我已經聲明並初始化了幾個Scope變量,並希望動態地訪問它們,但是當我嘗試從html文件訪問變量時,該變量被視為字符串。
JS代碼-
$scope.abc3txt = "Hello";
$scope.abc2txt = "hello everyone";
$scope.abc1txt = "hello 123";
在abc“數字”文本之間有一個數字,每個變量都像3、2、1。
我想根據html文件中的數字訪問變量值。
HTML代碼
<h4>{{abc+a.status+txt}}</h4>
a.status具有一些值,例如1,2或3。
這將在HTML中打印為“ abc3txt”,而不是返回變量“ $ scope.abc3txt”的初始化值。
請有人幫忙..
您絕對不應該在JavaScript中那樣使用變量名...
考慮使用數組...
這樣的事情應該有所幫助:
在控制器中:
$scope.a = {};
$scope.a.status = 2;
$scope.abctxt = [ "hello 123", "hello everyone", "Hello" ];
並且,在模板中:
<h4>{{ abctxt[a.status - 1] }}</h4>
我不知道是否可以直接用$scope
完成。 一種方法是將這些值保存在對象中:
$scope.values = {
abc3txt: "Hello",
abc2txt: "hello everyone",
abc1txt: "hello 123"
};
在您看來,您可以像這樣訪問它們:
{{values['abc' + a.status + 'txt']}}
編輯:最好的替代方法是使用controllerAs語法。 假設您在控制器中:
var vm = this;
vm.abc3txt = "Hello";
vm.abc2txt = "hello everyone";
vm.abc1txt = "hello 123";
然后在您的視圖中: {{vm['abc' + a.status + 'txt']}}
從所有可能的角度來看,以您尋求的方式動態生成變量名是非常非常 非常糟糕的做法,而這與語言可能支持(或缺乏支持)無關。 話雖如此,數組是正確的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.