Reputation: 9844
On my website users can use a inputfield to insert the title of a movie into the database. Now I want to show that title on the frontpage of the website.
I have made template for showing it,
%div{"ng-repeat" => "movie in movies"}
{{ movie.title }}
This is the controller,
angular.module('addMovieseat')
.controller('movieOverviewCtrl', [
'$scope', function($scope) {
$scope.movies = [
{
title: 'Star Wars'
}
]
}
]);
And now the title Star Wars
is shown on the frontpage. But I can't figure out how to combine this with my movies.json
file, which shows the values from the database.
I think I need to create a service and inject that service into the movieOverCtrl
but I can't find a propper example for it.
Upvotes: 0
Views: 59
Reputation: 9844
In the end I rememberd I did something like this on the Codecademy AngularJs tutorial.
The controller,
angular.module('addMovieseat')
.controller('movieOverviewCtrl', [
'$scope', 'movieService', function($scope, movieService) {
movieService.success(function(data) {
$scope.movies = data;
});
}
]);
And the serice,
angular.module('addMovieseat')
.factory('movieService', ['$http', function($http) {
return $http.get('movies.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}])
Upvotes: 0
Reputation: 7920
You can define a service which retrieve your json file using $http
service. Then you can inject that service to your controller to use your movie data in your views.
Check out the example:
var app = angular.module('addMovieseat');
app.factory("movieService", function("$http") {
var movieService = {
retrieveMovies: function() {
return $http.get("your-movie-file.json"); // return promise to your json file
}
};
return movieService;
});
app.controller('movieOverviewCtrl', [
'$scope', '$log', 'movieService'
function($scope, $log, movieService) {
function initCtrl() {
movieService.retrieveMovies().success(function(data, status, headers, config) {
$scope.movies = data;
}).
error(function(data, status, headers, config) {
// log error
});
}
initCtrl();
}
]);
Upvotes: 1
Reputation: 3842
Use $http to get data. Assign it to your scope property on success. Angular will do the rest.
function getMovies () {
$http.get('/movies')
.then(function (response) {
$scope.movies = response.movies;
});
}
Upvotes: 1