我在scripts.js中编写了以下Angular脚本:
// defining a Module
var myApp = angular.module("myApp", []);
// defining a controller as the child of the above module
myApp.controller("myController", function($scope){
$scope.authors = [
{ author : "Jack London", book : 'Martin Eden'},
{ author : "Thomas Hardy", book : 'Jude, the Obscure'},
{ author : "Emile Zola", book : 'Germinal'},
];
$scope.addNewAuthor = function(){
$scope.authors.push = function(){
author : $scope.newAuthor.name,
book : $scope.newAuthor.book,
},
};
});
然后我写了这个HTML视图:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<script type="text/javascript" src="angular.js" ></script>
<script type="text/javascript" src="scripts.js" ></script>
</head>
<body >
<h1>Hello</h1>
<div data-ng-controller="myController">
<ul data-ng-repeat="single in authors">
Author {{ single.author }} has written {{ author.book }}
</ul>
</div>
</body>
</html>
但是它不起作用而且在视野中而不是真实数据中,我从字面上得到了我所写的内容:
浏览器中的HTML输出:
Hello
Author {{ single.author }} has written {{ author.book }}
答案 0 :(得分:0)
实际上,你的javascript错了。这不是将项目推送到Array
的方式,必须将推送用作函数:
var myApp = angular.module("myApp", []);
// defining a controller as the child of the above module
myApp.controller("myController", function($scope){
$scope.authors = [
{ author : "Jack London", book : 'Martin Eden'},
{ author : "Thomas Hardy", book : 'Jude, the Obscure'},
{ author : "Emile Zola", book : 'Germinal'},
];
$scope.addNewAuthor = function(){
$scope.authors.push({
author : $scope.newAuthor.name,
book : $scope.newAuthor.book,
});
};
});
此外,您的HTML中存在拼写错误,您使用的是author.book而不是single.book:
<body ng-app="myApp">
<h1>Hello</h1>
<div data-ng-controller="myController">
<ul data-ng-repeat="single in authors">
Author {{ single.author }} has written {{ single.book }}
</ul>
</div>
</body>