Zequez
Zequez

Reputation: 3499

How do I separate data models and local-data models in Angular?

I hope I can expain myself what I mean.

Let's say I have a car resource. The car has the attributes color, name or whatever.

I get the list of cars using a service, something like cars.index().

But in the interface I have all the cars and when I click on one car, a little popup appears showing the inputs to edit the color and the name.

And here comes the issue. Where do I save the displayingInputs attribute?

  1. Should I save it directly in the car resource and then just send the original attributes when submitting to the updated resource?

  2. Should I create a new service called carWidget or something along the lines that each one has something like:

    {
      car: cars.get(carId),
      displayingInputs: false
    }
    
  3. Should I store the displayingInputs inside a carWidget directive scope? What happens if I need to change the `displayingInputs from the parent scope? (for example when making a "display all"/"hide all" button)

  4. Something else?

My best bet is #3, but I'm not sure how should I access the displayingInputs from outside the widget.

Upvotes: 0

Views: 138

Answers (1)

Mart
Mart

Reputation: 5798

If you want to keep your car model clean, you can have a separate variable editedCar and display each popup with ng-show="car == editedCar".

If multiple cars can be edited at the same time, editedCars can be an associative array (car ID => boolean) and display popups using ng-show="editedCars[car.id]".

Another way not to send certain car properties is to prefix their name with a $ sign. This was simply use car.$displayingInputs. Be careful for name collisions as Angular uses this prefix to store internal data.

From the angular.toJson doc:

Serializes input into a JSON-formatted string. Properties with leading $ characters will be stripped since angular uses this notation internally.

Upvotes: 1

Related Questions