我正在使用AngularJS。
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中的项目,但它不起作用。
答案 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放入你的范围,见下面的例子:
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;
请注意,目前还不清楚为什么要ng-init
,为什么不简单地循环myArray? ng-repeat = "user in myArray"