Giter Club home page Giter Club logo

angular-wp-api's Introduction

AngularJS Module for WP-API

There is also a Backbone.js WP-API client.

This library provides an AngularJS client-side interface for the WP API Plugin for WordPress.

Dependencies

Aside from AngularJS, this module relies on ngResource, a separate AngularJS module, to create API resources for your apps. This is a separate script you will need to include.

You will need to enqueue AngularJS in your theme or plugin, and have the WP-API plugin activated.

Inclusion

There are 2 methods of using this script. You can use the provided plugin, or bundle it with your app.

Set theme support

To include the script using the plugin, you'll just add a snippet to the theme or plugin containing your app.

There is one required parameter, and 2 optional configuration parameters. Here is the minimal code to enable the script:

add_theme_support( 'angular-wp-api' );

The first parameter designates what to support using a string - angular-wp-api.

The second parameter is the script dependency array. This is used to control where the script is enqueued, to ensure it has AngularJS and ngResource available, and that the script itself is available for your app.

The third parameter is an optional array of data to be localized with the script in the wpAPIData object.

add_theme_support( 'angular-wp-api',
	array(
		'mytheme-angular'
	),
	array(
		'data' => 'this is some data',
		'moredata' => 'more data wheee'
	)
);

Script dependencies and localized data can also be modified with the angular_wp_api_script_dependencies and angular_wp_api_local_data filters, respectively.

Now that you have set the dependency of the angular-wp-api script, add wp.api as a dependency of your app scripts to make sure it is accessible. If you get error messages in the console about missing objects, check this.

Bundling

If you would like to include the module in your scripts for concatentation with grunt or otherwise, you'll need to localize some data from within WordPress. See the plugin.php file for an example.

Use

wp.api in your Modules

To provide access to API resources, include wp.api in the dependency array of your module definition.

angular.module( 'myApp', [ 'wp.api' ] );

Local Data

The resources rely on localized data injected into the footer of the page, with the name of wpAPIData. By default, there are three values it provides, which allow access to the rest of WP-API.

  • base: JSON API url, provided by the json_url() function.
  • nonce: JSON API nonce sent with requests, and used for authorization.
  • user_id: Current user ID if logged in. Users not logged will have an ID of 0 for utility.

Getting Data

The resource takes 7 parameters ( the depth of WP-API's routing ) to designate the API route:

/:param1/:param2/:param3/:param4/:param5/:param6/:param7/

Additional parameters are added to the query string by ngResource.

Examples

This is an example of requesting base API information:

wpAPIResource.get();

A request for the current user data:

wpAPIResource.get( {
	param1: 'users',
	param2: wpAPIData.user_id
} );

** If the user is not logged in, the request will receive a 403 Forbidden response.

A single post request:

wpAPIResource.get( {
	param1: 'posts',
	param2: 1
} );

A post loop request:

wpAPIResource.query( {
	param1: 'posts'
} );

Creating a new post draft:

wpAPIResource.save( {
	param1: 'posts'
},
{
	title: 'Only a Test',
	slug: 'a-test',
	content: 'This is test content.'
} );

Updating a post title:

wpAPIResource.save( {
	param1: 'posts',
	param2: 1
},
{
	title: 'Hi World!'
} );

A post loop request for page 3 of posts:

wpAPIResource.query( {
	param1: 'posts',
	page: 3
} );

A request for registered post types:

wpAPIResource.query( {
	param1: 'posts',
	param2: 'types'
} );

A request for data about the attachment post type:

wpAPIResource.query( {
	param1: 'posts',
	param2: 'types',
	param3: 'attachment'
} );

The ngResource method .get(), should be used for requesting single objects/entities, as it expects an object to be returned. When requesting a loop/collection, use query(), which expects an array.

Development

To develop, build and test this library, you must have Node installed. For Windows users, simply download and install Node. For Mac users, we recommend installing Node using Homebrew. Once Homebrew is installed, run brew install node to install Node.js.

Installation

Clone this repository, and then execute the following commands within the checkout directory:

$ npm install

This will use Node's NPM package manager to install all the dependencies for building and testing this library. Grunt is installed automatically by the npm install command, and is used to run the build tasks.

Building

To update the JavaScript files in after you've made changes, run the library's build script with the npm command:

$ npm run build

This will use Grunt to check the source script for syntax errors, then minify it to create the minified angular-wp-api.min.js file and a corresponding source map file.

Testing

Coming soon . .

A note on Grunt

The custom "build" script defined in this library's package.json enable access to Grunt's functionality after a simple npm install; however, these commands can also be run directly using Grunt itself. In order to gain access to the grunt console command, you must globally install the Grunt command-line interface:

$ npm install -g grunt-cli

Once grunt-cli has been installed, you can run the build and test commands with grunt and grunt test, respectively, without having to invoke the scripts via NPM.

angular-wp-api's People

Contributors

baffleinc avatar dependabot[bot] avatar jason-cooke avatar jeffsebring avatar kadamwhite avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

angular-wp-api's Issues

Can't use filters

Hi Jeff,

this might not be an issue but I'm unable to use filters in my param.

This works in my controller..

$scope.newsletters = NewslettersFactory.query({
param1: 'posts'}, function(data) {
console.log("Got all", data);
});

But I'd like to specify posts?filter[category_name]='news'

How is this possible?

Use Restangular instead of ngResource

The current approach with ngResource forces you to use the ugly :param1/:param2 approach. I think it would be better to use Restangular instead. With Restangular you could create a service like this:

module.factory('wpAPIResource', function(Restangular) {
  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(wpAPIData.base);
    RestangularConfigurer.setDefaultHeaders({ 'X-WP-Nonce': wpAPIData.nonce });
  });
});

And then use it like this (example taken from Restangular README):

// Restangular returns promises
wpAPIResource.all('users').getList()  // GET: /users
.then(function(users) {
  // returns a list of users
  $scope.user = users[0]; // first Restangular obj in list: { id: 123 }
})

// Later in the code...

// Restangular objects are self-aware and know how to make their own RESTful requests
$scope.user.getList('cars');  // GET: /users/123/cars

// You can also use your own custom methods on Restangular objects
$scope.user.sendMessage();  // POST: /users/123/sendMessage

// Chain methods together to easily build complex requests
$scope.user.one('messages', 123).one('from', 123).getList('unread');

Still active?

Noticed the last commit was 2 years ago. Is this still under development at all? Saw you had mentioned a v2 in some comments and wondered if I should wait before using in a project.

Try an array instead of a `{ paramX: '' }` object for designing queries

Looking at the way queries are constructed with this library, I feel that the param1, param2 etc convention feels a bit arbitrary. Query levels (or directories, or what have you) will always start at the root (param1) and go until you don't specify another key; I'm not aware of a situation where you'd have a query for param1 and param3 without the intermediate param2.

Given this linearity, have you considered using an array for structuring these queries? As an example,

wpAPIResource.get( {
    param1: 'users',
    param2: wpAPIData.user_id
} );

would become

wpAPIResource.get([ 'users', wpAPIData.user_id ]);
// or
wpAPIResource.get([
  'users',
  wpAPIData.user_id
]);

This may avoid some confusion around the param1, param2 naming convention by flat-out removing it: You're now specifying a sequential number of URL parts that are assembled to create a final query.

Alternatively, you could introduce a more verbose query syntax in the manner of an ORM library like knex. That may be overkill for the time being!

wpAPIResource is not defined

I'm attempting to use this API for some dynamic post population and am running into an issue in configuring it.

JS:

var dbModule = angular.module('database', ['wp.api']);

dbModule.controller('ResultsController', function(){
    wpAPIResource.query({
        param1: 'posts'
    });
});

PHP:

add_theme_support('angular-wp-api', array('angular', 'angular-route', 'angular-resource'));

It throws this error every time:

ReferenceError: wpAPIResource is not defined
    at new <anonymous> (db.js?ver=4.2.2:4)
    at Object.invoke (angular.js?ver=4.2.2:4219)
    at $get.extend.instance (angular.js?ver=4.2.2:8525)
    at angular.js?ver=4.2.2:7771
    at forEach (angular.js?ver=4.2.2:334)
    at nodeLinkFn (angular.js?ver=4.2.2:7770)
    at compositeLinkFn (angular.js?ver=4.2.2:7149)
    at compositeLinkFn (angular.js?ver=4.2.2:7152)
    at publicLinkFn (angular.js?ver=4.2.2:7028)
    at angular.js?ver=4.2.2:1460

Dependencies are set properly as far as I can tell and WP-API is enabled. I am running this on a multi-site, could that be causing issues?

Thank you

ReferenceError: wpAPIData is not defined

Hi,
I'm trying to utilize angular-wp-api, and have some issue with 'wpAPIData'.
I read your answer to @joao-parana, but still not fully understand the way of solution.
I already added within my wordpress json-rest-api/plugin.php the code
you specified as is,
but not sure where to add the theme support for 'angular-wp-api' ??
then on running angular app the ctrl recognized 'wpAPIResource' but not 'wpAPIData' obj, receiving this error:
ReferenceError: wpAPIData is not defined

.controller('SliderCtrl',function($scope, $timeout, $ionicSlideBoxDelegate, $http, wpAPIResource, wpAPIData) { ... }

where is the mistake?

$injector is unable to resolve a required dependency : wpAPIDataProvider

I don't know how to resolve this issue.

wpAPIResource is injected successfully but wpAPIData not !

My controller:

  // Wordpress Resource Support
  app.controller('WPRemoteFetchCtrl',
    function ($scope, wpAPIResource, wpAPIData) {
      $scope.wordpress = {};
      $scope.wordpress.root = wpAPIResource.get();
      $scope.wordpress.post1 = wpAPIResource.get( {
          param1: 'posts',
          param2: 1
      });
      $scope.wordpress.user = wpAPIResource.get( {
          param1: 'users',
          param2: wpAPIData.user_id
      });
  });

Any Ideas ?

Can't find variable: wpAPIResource

I've enabled the "AngularJS WordPress API" plugin but the page is not loading the 'angular-wp-api.min.js' javascript file.

What is going wrong?

Note:
When I run wpAPIResource.get(); I get the error "Can't find variable: wpAPIResource"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.