我正在尝试找到一种方法,允许我从数组(或JSONP输出)中保存特定数据。
让我说我有这个,
function Ctrl($scope) {
$scope.movies = [
{'title' : 'Star Wars', 'id' : '1'},
{'title' : 'Inception', 'id' : '2'},
{'title' : 'Inherent Vice', 'id' : '3'}
];
}
我显示结果,
<div ng-controller="Ctrl">
<div ng-repeat="movie in movies">
{{ movie.id }} : {{ movie.title }} - <a href="#">Add Movie to watchlist</a>
</div>
</div>
当您点击add movie to watchlist
时,我想将该影片标题和ID存储在范围内,以便稍后使用。我怎么能这样做?
以下是plunkr示例http://plnkr.co/edit/tycuNmJy71Yr4SUia2e5?p=preview
答案 0 :(得分:3)
尝试此代码:: Demo
HTML:
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-repeat="movie in movies">
{{ movie.id }} : {{ movie.title }} - <a href="#" ng-click="addMovie(movie)">Add Movie to watchlist</a>
</div>
WishList: {{wishlist}}
</div>
</body>
</html>
控制器:
function Ctrl($scope) {
$scope.movies = [
{'title' : 'Star Wars', 'id' : '1'},
{'title' : 'Inception', 'id' : '2'},
{'title' : 'Inherent Vice', 'id' : '3'}
];
$scope.wishlist = [];
$scope.addMovie = function(movie)
{
$scope.wishlist.push({id: movie.id, title: movie.title});
}
}
答案 1 :(得分:0)
我将这个功能添加到你的plnkr
function Ctrl($scope) {
$scope.movies = [
{'title' : 'Star Wars', 'id' : '1'},
{'title' : 'Inception', 'id' : '2'},
{'title' : 'Inherent Vice', 'id' : '3'}
];
$scope.select = function (movie) {
//do your stuff here
console.log(movie.title);
}
}
<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-repeat="movie in movies">
{{ movie.id }} : {{ movie.title }} - <a href="#" ng-click="select(movie)">Add Movie to watchlist</a>
</div>
</div>
</body>
</html>
答案 2 :(得分:0)
是的,您可以编写一个函数,您可以在其中传递所选项的ID并将其存储在范围变量中。 如下所示:
$scope.getDetails = function(id){
alert(id);
$scope.storedMovie = $scope.movies[id].title;
alert($scope.storedMovie)
}