Drupal and AngularJS
Do you have drush?
apt-get install drush
Install drupal:
drush pm-download --drupal-project-rename=drupal
cd drupal
Yo can see status:
drush status
Prepare a mysql database and then run this command:
drush site-install --db-url=mysql://drupal:drupal@127.0.0.1/drupal --account-mail=admin@bdunk.com --account-name="admin" --account-pass="here your pass" standard
If you have Nginx like webserver there is a nice configuration file sample here.
We need to install “views” (in Drupal 8 this module belongs to the core):
drush dl views
drush en views
drush en views_ui
And install a module named Views Datasource.
drush dl views_datasource
drush en views_json
Now it’s time to create your own content. In my case I created a list of dogs. Just contains the following fields:
- title
- Body
- Photo
And create a new view to show this content. Edit this view, most important is:
- Format: Choose JSON Document. In this sections select “JSON data format” > “MIT Simile/Exhibit”.
- Fields: Select all required fields.
- Photo field: in “Formatter” select “URL to file”.
We have now a url like this http://localhost/dogs-json and result it’s
{"Items":[{"node":{"title":"Je je je","Body":"Niki Niki.\n","Post date":"Monday, November 3, 2014 - 18:54","Photo":"http:\/\/192.168.0.21:81\/sites\/default\/files\/perrete_abrazo.jpg"},"label":"Item","type":"node"},{"node":{"title":"Another perrete","Body":"OMG!!!\n","Post date":"Monday, November 3, 2014 - 15:04","Photo":"http:\/\/192.168.0.21:81\/sites\/default\/files\/perrete_comida.jpg"},"label":"Item","type":"node"},{"node":{"title":"Perrete","Body":"It's a good animal\n","Post date":"Monday, November 3, 2014 - 14:52","Photo":"http:\/\/192.168.0.21:81\/sites\/default\/files\/perrete_guarrindongo.jpg"},"label":"Item","type":"node"}]}
Finally let’s go with Angular JS.
You only need a sample like “Hello Angular JS”.
In this sample controller is:
angular.module("dogs", [])
.controller("DogController", function($scope, $http) {
$scope.dogs="";
$http.get('/dogs-json').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
$scope.dogs=data.Items;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
);
HTML code:
<html lang="en" ng-app="dogs">
...
<div class="container" ng-controller="DogController">
<div ng-repeat="dog in dogs">
<h3></h3>
<p></p>
<p>
<img ng-src="" class="img-responsive" alt="Responsive image">
</p>
</div>
</div>
...
The result:
I don’t like work with Drupal’s templates and I think this could be a better way if you want a clean code.
Cheers!