gpt4 book ai didi

javascript - AngularJS 工厂服务

转载 作者:行者123 更新时间:2023-12-03 08:40:27 27 4
gpt4 key购买 nike

我正在尝试在我的应用程序中使用工厂服务功能将电影添加到我的列表中。我已经能够从列表中删除电影,但我无法弄清楚为什么无法将电影添加到当前列表中。

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>

最佳答案

首先,您的 addMovie 函数无法访问 movie,因此它可能会在控制台中抛出错误。更改此:

factory.addMovie = function(){

factory.addMovie = function(movie) {

并更改此:

$scope.addMovie = function(){
MoviesService.addMovie();
}

至:

$scope.addMovie = function() {
MoviesService.addMovie($scope.movie);
}

始终注意控制台错误。我在行动中制作了一个工作插件:

http://plnkr.co/edit/AXNhovhKrW24FLOt9KGM?p=preview

关于javascript - AngularJS 工厂服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33046936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com