问题描述
我写一个角度应用程序,与谷歌Analytics(分析)API已在使用接口。由谷歌返回的数据与pfixed $ P $嘎:作为例子。嘎:newVisits
如果我使用ex pression {{total.ga:newVisits}},角不能解析它。在逃逸结肠继续任何企图导致错误或干脆逃离我的前妻pression。
如何传递{{total.ga:newVisits}}到角,使得前pression将正常工作?
<!DOCTYPE HTML>
< HTML NG-应用=AnalyticsApp>
< HEAD>
&所述; SCRIPT SRC =https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js>&下; /脚本>
&所述; SCRIPT SRC =角controller.js>&下; /脚本>
< /头>
<机身NG控制器=AnalyticsCtrl>
< UL>
<李NG重复=总的结果>
{{total.ga:newVisits}}
< /李>
< / UL>
< /身体GT;
< / HTML>
在JavaScript中,对象的属性可以通过点符号或括号标记访问。点符号往往吸尘器,但限制。正如你已经注意到了,你的属性包含无效字符,因此无法通过点符号来访问。该解决方案,那么,是用括号符号这样的访问属性:总['GA:newVisits']
让你彻底code将 {{总['GA:newVisits]}}
。
有关括号标记另一个优点是,它允许你使用一个变量名作为一个属性:
VAR MyObj中{
酒吧:'123'
};
无功富='吧';的console.log(MyObj中[富]); //日志'123'
I am writing an Angular app that interfaces with a Google Analytics API already in use. The data returned by Google is prefixed with "ga:" as in the example "ga:newVisits".
If I use the expression {{total.ga:newVisits}}, Angular cannot parse it. Any attempts at escaping the colon to continue has resulted in an error or escaping my expression altogether.
How can I pass {{total.ga:newVisits}} to Angular so that the expression will work properly?
<!doctype html>
<html ng-app="AnalyticsApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="angular-controller.js"></script>
</head>
<body ng-controller="AnalyticsCtrl">
<ul>
<li ng-repeat="total in result">
{{total.ga:newVisits}}
</li>
</ul>
</body>
</html>
In JavaScript, object properties can be accessed by dot notation or bracket notation. Dot notation is often cleaner, but has restrictions. As you have noticed, your property contains an invalid character and therefore can't be accessed via dot notation. The solution, then, is to access the property using bracket notation like this: total['ga:newVisits']
so that your complete code will be {{total['ga:newVisits']}}
. Live demo here (click).
Another nice feature about bracket notation is that it allows you to use a variable name as a property:
var myObj {
bar: '123'
};
var foo = 'bar';
console.log(myObj[foo]); //logs '123'
这篇关于如何访问与无效字符对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!