将一个数组设置为angularJS中的范围不起作用

时间:2015-02-19 19:40:55

标签: angularjs angularjs-scope

我正在使用AngularJS。

Fiddle

var myArray = [{firstName: 'Jane', lastName: 'Doe', age:29},
{firstName: 'John', lastName: 'Doe', age: 32}]; 

HTML

<body ng-app="" ng-init="users = myArray">

    <div ng-repeat="user in users">
         {{user.firstName}} {{user.lastName}} - Age: {{user.age}}
    <div>
</body>

这里在小提琴中我想将MyArray设置为ng-init中的项目,但它不起作用。

2 个答案:

答案 0 :(得分:0)

Angular对你的数组没有任何线索,除非你把它链接起来(在控制器或int html中使用model / $ scope),看看它现在正在我用ng-init声明它

  <body ng-app="" 
        ng-init="users = [
   {firstName: 'Jane', lastName: 'Doe', age:29}, 
   {firstName: 'John', lastName: 'Doe', age: 32}
  ]">

    <div ng-repeat="user in users">
         {{user.firstName}} {{user.lastName}} - Age: {{user.age}}
    <div>
</body>

答案 1 :(得分:0)

当您在HTML中编写表达式(例如users = myArray)时,您使用的变量需要位于控制器的$scope中。所以你需要将myArray放入你的范围,见下面的例子:

&#13;
&#13;
angular.module("test", []).controller("test", function($scope) {
  $scope.myArray = [
    {firstName: 'Jane', lastName: 'Doe', age:29},
    {firstName: 'John', lastName: 'Doe', age: 32}
  ];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="test" ng-controller="test">
  <div ng-init="users = myArray">
    <div ng-repeat="user in users">
      {{user.firstName}} {{user.lastName}} - Age: {{user.age}}
    <div>
  </div>
</body>
&#13;
&#13;
&#13;

请注意,目前还不清楚为什么要ng-init,为什么不简单地循环myArray? ng-repeat = "user in myArray"