Angular的新功能,我花了2个小时搜索我的错误,通过一些文档帮助并观看已有的帖子但没有任何事情可做..
我只是很难声明一个对象数组并试图遍历它:
代码:
angular.module('MyAppModule', [ ])
.controller('GreetsController', ['$scope', function ($scope) {
$scope.name = prompt('What\'s your name ?');
}])
.controller('ListController', ['$scope', function ($scope) {
$scope.personNb = this.persons.length;
$scope.persons = [
{
image: 'images/images(1).jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/images.jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/téléchargement.jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/téléchargement(1).jpg',
name: 'John Doe',
age: 23
}
];
}]);
HTML:
<div ng-controller="GreetsController">
<h1>Coding with AngularJs</h1>
<h2 ng-show="name">{{"Welcome " + name + " !"}}</h2>
</div>
<div ng-controller="ListController" ng-repeat="person in persons">
<h3>{{person.name}}</h3>
<h3>{{person.age}}</h3>
</div>
{{ListController.persons[0].age}}
<h3 ng-show="{{ListController.person_nb}}">There is a total of {{ListController.person_nb}} register</h3>
我没有捕获它,但所有脚本都包含在内,我在app.js的depedencies数组中添加了'MyAppModule'
答案 0 :(得分:3)
您的 HTML
中有3个错误您必须在致电控制器之前声明ng-app
,然后将其放在上面的一个标签中:
因此,您的 HTML 会变为:
<div ng-app="MyAppModule">
<div ng-controller="GreetsController">
<h1>Coding with AngularJs</h1>
<h2 ng-show="name">{{"Welcome " + name + " !"}}</h2>
</div>
<div ng-controller="ListController" ng-repeat="person in persons">
<h3>{{person.name}}</h3>
<h3>{{person.age}}</h3>
</div>
{{ListController.persons[0].age}}
<h3 ng-show="{{ListController.person_nb}}">There is a total of {{ListController.person_nb}} register</h3>
</div>
答案 1 :(得分:0)
你有两个错误:
<div ng-controller="ListController" ng-repeat="person in persons">
将ng-controller和ng-repeat分解为不同的元素。您不想重复控制器。 $scope.personNb = this.persons.length;
this.persons不存在。ListController
访问控制器的底部摘要。查看我所做的更改。点击Run code snippet
进行演示。
angular.module('MyAppModule', [ ])
.controller('GreetsController', ['$scope', function ($scope) {
$scope.name = "";
$scope.name = prompt('What\'s your name ?');
}])
.controller('ListController', ['$scope', function ($scope) {
$scope.persons = [
{
image: 'images/images(1).jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/images.jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/téléchargement.jpg',
name: 'John Doe',
age: 23
},
{
image: 'images/téléchargement(1).jpg',
name: 'John Doe',
age: 23
}
];
$scope.personNb = $scope.persons.length;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyAppModule">
<div ng-controller="GreetsController">
<h1>Coding with AngularJs</h1>
<h2 ng-show="name">Welcome {{name}}!</h2>
</div>
<div ng-controller="ListController">
<div ng-repeat="person in persons">
<h3>{{person.name}}</h3>
<h3>{{person.age}}</h3>
</div>
{{persons[0].age}}
<h3 ng-show="{{personNb}}">There is a total of {{personNb}} register</h3>
</div>
</div>