Angular 1.2.0:错误:尝试访问Mongo _id字段时"不允许在Angular表达式中引用私有字段"

cod*_*sky 7 mongodb angularjs

尝试从角度表达式中读取mongo _id字段时:

<tr ng-repeat="person in people">
  <td>{{person._id}}</td>
  <td>{{person.name}}</td>
  <td>{{person.location}}</td>
  <td>{{person.active}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

抛出以下错误:

"Referencing private fields in Angular expressions is disallowed"
Run Code Online (Sandbox Code Playgroud)

plunker链接:http://plnkr.co/edit/dgHNP2rVGPwAltXWklL5

编辑:

此更改已在Angular 1.2.1中恢复:https://github.com/angular/angular.js/commit/4ab16aaaf762e9038803da1f967ac8cb6650727d

cod*_*sky 6

当前的解决方案

这是由于Angular 1.2.0的突破性变化(在此讨论:https://github.com/angular/angular.js/commit/3d6a89e)

对此有一个简单的,如果不是烦人的解决方案.

app.run函数中,您可以添加$ rootScope级别访问者对象,该对象包含一个函数以返回正确的Mongo ID.

app.run(function($rootScope) {
  $rootScope.accessors = {
    getId: function(row) {
      return row._id
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

然后,在您的标记中,使用该方法而不是直接访问数据点:

<tr ng-repeat="person in people">
  <td>{{accessors.getId(person)}}</td>
  <td>{{person.name}}</td>
  <td>{{person.location}}</td>
  <td>{{person.active}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)

一个带有修复程序的plunker:http://plnkr.co/edit/NcRrKh

讨论:

这将允许您继续进行开发,但是知道它确实带来了比直接访问变量更多的开销.对于小型项目,这不应该影响任何可察觉级别的性能,尽管您可能会在较大的应用程序上看到一些可测量的数量.然而,就目前而言,这种担忧纯粹是学术性的.

  • 此功能已恢复.https://github.com/angular/angular.js/commit/4ab16aaaf762e9038803da1f967ac8cb6650727d (2认同)