3

I'm used to see in MVC Pattern view, controller and model separated and now in many How To I can see model implemented in controller and for me this practice doesn't respect MVC Pattern.

In my case, what I want is for example :

a POJO Car :

    public class Car
    {
     private int price;
     private int doors;

     public Car (int px, int dr)
     {
        this.price = px;
        this.doors = dr;
    }
   }

And after instanciation in my java programme

Car car = new Car(1000, 4);

Now, how can I to put this object into Angular's model please ?

Thanks in advance.

  • Javascript code can't access java variables directly. Two different ways of passing the data from the java code to the javascript code is 1.) Have a jsp page that renders a JSON object to the page that your javascript code can use. 2.) Create a RESTful web service where the javascript code can request the data. – Simon Mar 17 '15 at 08:34

4 Answers4

4

I usually use the following pattern

angular.module('yourServiceName.car.model', [])
.factory('Car', function() {
    function Car(car) {
        /* extend with lodash.
         * Since this is a POJO, don't transform anything you dont need.
         */
        _.assign(this, car, this); 
    }

    Car.Enums = {SOME:1, ENUM:2, YOU:3, MIGHT:4, NEED:5};

    Car.prototype.method = function() {
        /* some model specific method.
         * don't throw REST or UI things here tho.
         */
    } 

    Car.create = {
        fromJSON: function(json) {
            /* only use this for JSON missing transformations, like
             * 'Y'|'N' to true|false
             * dateString to Date instance
             */
            json.startDate = Date.parse(json.startDate); or something.

            // I want to see 'Car' in my debug window, instead of 'Object'
            return new Car(json);
        }
    }

    return Car;
});

Then on your API service

angular.module('yourService.car.rest', [
    'yourService.car.model'
])
.factory('carApi', function(baseURL, Car) {
    var path = baseURL+'/car'
    var Routes = {
            CREATE : path,
            LIST   : path+'/%s',
            DETAILS: path+'/%d'
        };

    function getCar(id, params) {
        // this should blowup if id is not a number
        var url = sprintf(Routes.DETAILS, id);
        return $http.get(url, params).then(function(response.data) {
            // if now JSON transformations are done
            // return new Car(response.data);

            return Car.create.fromJSON(response.data);
        });
    }

    function listCars(ids, params) {
        ids = ids || [];
        var _ids = ids.join(',');
        var url = sprintf(Routes.LIST, _ids);
        return $http.get(url, params).then(function(response) {
            return _.map(response.data, Car.create.fromJSON);
        });
    }

    function createCar(oCar) {
        /* Hungarian notation indicates I expect an instance of 'Car'
         * And not just any object
         */

        $http.post(Routes.CREATE, {data: oCar});
    }

    return  {list:listCars, get:getCar, create:createCar};
});

So finally in your controller, you would have something like

angular.module('yourProject.ui.car.list', [
    'yourServiceName.car.model',
    'yourServiceName.car.rest'
])
.controller('ListCarsController', function ListCarsCtrlr(carsApi, Car) {
    $scope.ids = [1, 2, 3];

    $scope.load = function() {
        var params = {}; // anything else you need to pass
        carsApi.list(ids, params).then(function(cars) {
            $scope.cars = cars; // all of these are now instanceof Car
        })
    }
});

Your controller ends up as simple as this:

enter image description here

You can even take it up a nodge if you need Viewmodel

angular.module('yourProject.ui.car.list.viewmodel', [
    'yourService.car.model'
])
.factory('CarItemViewmodel', function CarItemVM() {
    function CarItemViewmodel(oCar) {
        // do some flattening or something you can unit test
        this.price = oCar.additionalAttributes.somethingDeep.price;
        this.ammount = oCar.someOtherStuff[0].quantity;
    };

    return CarItemViewmodel;
});
percebus
  • 799
  • 1
  • 8
  • 21
2

MVC patter of angularjs means that all layer(M,V,C) are in client side. In this pattern, Server side normally return simple json file which are requested by ajax wheter you implement your server side code with MVC pattern or not.

Therefore If you prefer to use POJO on your server side code, I suggest to conver POJO to json format and serve it as json file. In the client angularjs code, you can convert json to javascript simple object and use it as model.

yazaki
  • 1,724
  • 1
  • 13
  • 17
0

You don't. And you can't.

You can make a web service in Java. You can make Angular to call that web service. But you can't push data from Java into "Angular's model", because that's not how the web works.

Community
  • 1
  • 1
ytg
  • 1,755
  • 2
  • 23
  • 41
0

override the tostring method of your Car class

public String toString(){
        return new JSONObject(this).toString();
    }

And you can put that object in json and return it as a json

Car car = new Car(1000, 4);

JSONObject jsonReturn = new JSONObject();
jsonReturn.put("car ", car );
ap.singh
  • 1,150
  • 4
  • 15
  • 35