admin管理员组

文章数量:1289565

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=".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>

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./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>
Share Improve this question edited Jan 29, 2014 at 0:58 m59 43.8k14 gold badges121 silver badges139 bronze badges asked Jan 10, 2014 at 23:02 VSackVSack 4791 gold badge4 silver badges11 bronze badges 1
  • {{total['ga:newVisits']}} – dave Commented Jan 10, 2014 at 23:06
Add a ment  | 

2 Answers 2

Reset to default 10

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 plete 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'

You need to access it as if it were an associative array:

{{total['ga:newVisits']}}

本文标签: javascriptHow to access object property with invalid charactersStack Overflow