我正在尝试在我的应用中使用工厂服务功能将电影添加到我的列表中。我已经能够从列表中删除一部电影,但我无法弄清楚为什么我不能将电影添加到当前列表中。
var app = angular.module('application', []);
app.factory("MoviesService",[function(){
var movies = [
{title:"Avengers: Age of Ultron",rating:"PG-13",year:"2015"},
{title:"Ant-Man",rating:"PG-13",year:"2015"},
{title:"The Martian",rating:"PG-13",year:"2015"},
{title:"San Andreas",rating:"PG-13",year:"2015"},
{title:"Jurassic Park",rating:"PG-13",year:"2015"},
{title:"Dope",rating:"PG-13",year:"2015"}
];
var factory = {};
factory.getMovies = function(){
return movies;
};
factory.addMovie = function(){
var newMovie = {
title: movie.title,
rating: movie.rating,
year: movie.year
}
movies.push(newMovie);
};
factory.removeMovie = function(movie){
var index = movies.indexOf(movie);
movies.splice(index,1);
};
return factory;
}]);
app.controller('CustomerController',['$scope','MoviesService',function($scope,MoviesService){
$scope.movies = MoviesService.getMovies();
$scope.removeMovie = function(movie){
MoviesService.removeMovie();
};
$scope.addMovie = function(){
MoviesService.addMovie();
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app = "application">
<div class = "row">
<div class = "col-md-12" ng-controller = "CustomerController">
<table class="table">
<caption>Optional table caption.</caption>
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Year</th>
<th>Rating</th>
<th>Options</th>
</tr>
<tr>
<th>Add</th>
<th><input ng-model="movie.title" class="form-control"></th>
<th><input ng-model="movie.year" class="form-control"></th>
<th><input ng-model="movie.rating" class="form-control"></th>
<th>
<button class = "btn btn-success" ng-click="addMovie()"><span class = "glyphicon glyphicon-plus"></span></button>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "movie in movies">
<th scope="row">{{$index}}</th>
<td>{{movie.title}}</td>
<td>{{movie.year}}</td>
<td>{{movie.rating}}</td>
<td>
<button ng-click="removeMovie(movie)" class="btn btn-danger">
<span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
答案 0 :(得分:1)
首先,您的addMovie功能无法访问movie
,因此可能会在控制台中抛出错误。改变这个:
factory.addMovie = function(){
到
factory.addMovie = function(movie) {
并改变这一点:
$scope.addMovie = function(){
MoviesService.addMovie();
}
为:
$scope.addMovie = function() {
MoviesService.addMovie($scope.movie);
}
始终注意控制台错误。我在行动中做了一个有效的工作人员:
答案 1 :(得分:0)
在addMovie
函数中,您尝试从movie
变量中添加一个在此上下文中不存在的影片。所以你可能在那里遇到错误。
答案 2 :(得分:0)
看起来你正在尝试做类似的事情:
$scope.movie = {}; // add this
$scope.addMovie = addMovie; // modify to this
...
factory.addMovie = function(movie){ // add parameter movie
movies.push(movie);
};
...
试一试。