ng-repeat变量范围到DOM块

时间:2014-06-10 17:03:00

标签: angularjs

我是在做梦还是在某个地方真的看到了,但我无法记住确切的语法。所以,如果我有

var fooObjects = [{ name:"John", age:15 }, 
                  { name: "Michael", age:26 }, 
                  ...etc...]

<div ng-repeat="for foo in fooObjects">     <-- note, this isn't real syntax
   {{name}}              <-- Now you don't have to explicitly call `foo.name`
   {{age}}                                          inside of this div block
</div>

1 个答案:

答案 0 :(得分:1)

来自https://docs.angularjs.org/api/ng/directive/ngRepeat的示例。尝试这样的事情:

  <div ng-init="friends = [
  {name:'John', age:25, gender:'boy'},
  {name:'Jessie', age:30, gender:'girl'},
  {name:'Johanna', age:28, gender:'girl'},
  {name:'Joy', age:15, gender:'girl'},
  {name:'Mary', age:28, gender:'girl'},
  {name:'Peter', age:95, gender:'boy'},
  {name:'Sebastian', age:50, gender:'boy'},
  {name:'Erika', age:27, gender:'girl'},
  {name:'Patrick', age:40, gender:'boy'},
  {name:'Samantha', age:60, gender:'girl'}
  ]">
    <ul>
      <li ng-repeat="friend in friends">
        {{friend.name}} who is {{friend.age}} years old.
      </li>
    </ul>
  </div>

这是一个带有示例http://plnkr.co/edit/I19oBk20T5ldLZe7GYqN?p=preview

的plunker

<强> - 编辑 -

我误解了你早先的问题。您可以通过在控制器中实现以下内容来对ng-repeat中的变量进行别名处理:

$scope.scopify(scope, object) {
  for (var o in object) {
    scope[o] = object[o];
  }
}

使用如下:

<li ng-repeat="friend in friends" ng-init="scopify(this, friend)">  
  {{name}}, {{age}}, {{gender}}
</li>

这是一个带有工作示例的plunker:http://plnkr.co/edit/Y8c4uOagcdM5cXN81TET?p=preview

除了上面的示例,您还可以通过ng-init指令为对象的任何属性创建别名。例如,另一种可能的解决方案是:

<li ng-repeat="friend in friends" 
    ng-init="name = friend.name; age = friend.age; gender = friend.gender">
  {{name}}, {{age}}, {{gender}}
</li>

我们可以使用ng-init创建我们可以在该html块中引用的别名。虽然如果你只想引用每个属性一次,这不是很有用,如果你必须在html块中多次重复相同的属性,它可能会派上用场。