加载页面时收到错误。我试图将一个新对象附加到一个条目数组中。
代码有什么问题?
的index.html
<div ng-controller="RaffleCtrl">
<form ng-sumbit="addEntry">
<input type="text" ng-model="newEntry.name">
<input type="submit" value="Add">
</form>
<ul>
<li ng-repeat="entry in entries">{{entry.name}}</li>
</ul>
</div>
raffle.js
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
]
});
$scope.addEntry = function () {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};
答案 0 :(得分:8)
您在控制器外部错误地使用了$scope
。使用控制器内的$scope
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
];
$scope.addEntry = function () {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};
});
答案 1 :(得分:1)
如果你真的想把它放在外面
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
];
$scope.addEntry = addEntry;
});
function addEntry() {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};