此代码示例在此小提琴http://jsfiddle.net/viralpatel/aLDJJ/中不起作用,但适用于同一作者的演示:http://viralpatel.net/blogs/angularjs-controller-tutorial/。 由于它也在我的小提琴上失败了,我很欣赏任何有关正在发生的事情的见解。
<!DOCTYPE html>
<html ng-app>
<head>
<title>Hello World, AngularJS - ViralPatel.net</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
</head>
<body>
<div ng-controller="ContactController">
Email:<input type="text" ng-model="newcontact"/>
<button ng-click="add()">Add</button>
<h2>Contacts</h2>
<ul>
<li ng-repeat="contact in contacts"> {{ contact }} </li>
</ul>
</div>
<script type="text/javascript">
function ContactController($scope) {
$scope.contacts = ["hi@email.com", "hello@email.com"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
ng-model
input
的{{1}}位于contact
,正在寻找$scope.newcontact
。改变这一点,它有效:http://jsfiddle.net/aLDJJ/157/
function ContactController($scope) {
$scope.contacts = ["viralpatel.net@gmail.com", "hello@email.com"];
$scope.add = function() {
$scope.contacts.push($scope.contact); //Changed here
$scope.contact = ""; //Changed here
}
}
<input type="text" ng-model="contact" />
答案 1 :(得分:0)
你的小提琴有一个与范围绑定的不同变量contact
。您正在进入contacts数组的变量是newcontact
,它未在范围中定义。为了清楚起见,我更改了对此变量的所有引用并将其命名为newContact
。
这个小提琴将起作用:http://jsfiddle.net/GruyereEmmentaler/aLDJJ/158/
<div ng-app="" ng-controller="ContactController">
Email:<input type="text" ng-model="newContact" />
<button ng-click="add()">Add</button>
<h2>Contacts</h2>
<ul>
<li ng-repeat="contact in contacts"> {{ contact }} </li>
</ul>
</div>
和javascript:
function ContactController($scope) {
$scope.contacts = ["viralpatel.net@gmail.com", "hello@email.com"];
$scope.add = function() {
$scope.contacts.push($scope.newContact);
$scope.newContact = "";
}
}