【发布时间】:2015-11-03 22:23:00
【问题描述】:
我创建了一个简单的指令来显示我的电影范围内的所有电影
app
.directive('movieOverview', function () {
return {
template: '<div ng-repeat="movie in movies">Name: {{movie.title}}</div>',
controller: 'searchCtrl',
};
});
但是当我将指令添加到我的application.html.erb 时,它不会在将新记录添加到电影范围时更新。我必须刷新页面才能看到新记录。
我认为指令可以在作用域之外使用。
这是我的 searchCtrl 中的 addMovie 函数(我与指令一起使用)。
$scope.addMovie = function() {
'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
// Search for release dates using the ID.
var base = 'http://api.themoviedb.org/3/movie/';
var movieID = $(event.currentTarget).parent().find('.movieID').text()
var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
var append_to_response = '&append_to_response=releases'
var callback = 'JSON_CALLBACK'; // provided by angular.js
var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;
$http.jsonp(url,{ cache: true}).
success(function(data, status, headers, config) {
if (status == 200) {
$scope.movieListID = data;
console.log($scope.movieListID);
var releaseNL;
for (var i = 0; i < $scope.movieListID.releases.countries.length; i++) {
var release = $scope.movieListID.releases.countries[i];
if (release['iso_3166_1'] == 'NL') {
releaseNL = release;
}
}
if(typeof releaseNL === 'undefined'){
// With release date
Notification($scope.movieListID.original_title + ' is toegevoegd, maar heeft nog geen Nederlandse premiere datum.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: $scope.movieListID.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
} else {
Notification.success($scope.movieListID.original_title + ' is toegevoegd.');
createMovie.create({
title: $scope.movieListID.original_title,
release_date: releaseNL.release_date,
image: $scope.movieListID.poster_path,
movie_id: $scope.movieListID.id
}).then(init);
};
重要的是看到这里是.then(init);
var init = function(){
movieService.loadMovies().then(function(response) {
$scope.movies = response.data;
});
}
init();
我添加一部电影,然后执行初始化函数,该函数会触发一个名为 loadMovies 的服务
.factory('movieService', ['$http', function($http) {
return {
loadMovies: function() {
return $http.get('/movies.json');
}
};
}])
请求新电影,然后更新视图。
【问题讨论】:
-
您可以将添加电影的代码添加到您的范围吗?
-
@thsorens 我已经从我的控制器中添加了代码。
-
我可能会在你的 json 文件中寻找缓存。与其重新加载所有内容,不如将结果推送到您的电影列表中? $scope.movies.push(thenewmovie);
-
您能否进一步扩展您的建议?
标签: angularjs angular-directive