Mathias Nielsen
Mathias Nielsen

Reputation: 1620

Reusing server-side models in AngularJS

So, I am looking to build something with AngularJS. Liking what I see so far, but there is something nagging me.

How do I make angular generate forms (and possibly routes) by looking at my model definitions?

I obviously have to translate the Python to Javascript and send it to the client, but can Angular do this? Is it possible to generate CRUD interfaces by looking at the models? I cant seem to find any info on this and I would rather not spend a lot of time on angular if this is impossible or very difficult.

If angular is not well suited for this, any suggestions for a javascript framework that is?

Upvotes: 3

Views: 504

Answers (2)

Romeo Mihalcea
Romeo Mihalcea

Reputation: 10252

What you want is what I want but it's not possible. You want to stay DRY by not rewriting models both in client and server. You could write a competent API but there's no client lib/ui to consume it the way you need. Check my comment on this matter:

http://caines.ca/blog/programming/so-i-wrote-a-json-api-framework-and-the-framework-was-the-least-interesting-part/comment-page-1/#comment-1893

Nonetheless, if you find it let me know. Writing server code to make the client happy is bad. Server is boss, rest should follow.

Upvotes: 0

ben schwartz
ben schwartz

Reputation: 2589

I'm not sure what your specific need is (let me know and I can elaborate,) but I think the best way to accomplish what you're looking for is to invest some time developing a REST interface.

Defining each python model as a resource will take the guess work out of the interface. There are even concepts in REST for defining "rel" links which expand upon what states are available to transition to.

Say you have a back end User model that looks like:

{
    id: 1,
    name: "Bob Loblaw",
    email: "[email protected]"
}

You could expose this model as a resource accessible at /user

Then in your client code you could create a User service which returns $resource('/user/:userId', {userId:'@id'});

Now that you have your User resource (accessible via a User service you have wired into your module...) All you need is to inject the resource into your controller and hack away:

// grab a user to display
$scope.user = User.get({userId:1});

// perform an update on a user
var user = User.get({userId:1}, function() {
    user.email = '[email protected]';
    user.$save();
});

// delete a user
User.delete({userId:1});

// etc...

Rather than automating model & route generation based on back end code, see if developing a restful interface which is self-defining would serve your needs.

Upvotes: 1

Related Questions