Martin
Martin

Reputation: 24308

Using reusable models and injecting these where required in Angular

Anyone know the best recommended way of creating models in a separate JavaScript file and have these injected into the controllers that need them, rather than creating the models on fly normally in the controller?

This would make it so much easier to pass around the model and you would know exactly what you was passing around.

I have some thoughts on using Services, and inject these where I need i.e. controllers.

Controllers would then pass these onto specific services to do any heavy lifting to keep my controllers nice and light.

Is services the only and recommended way to go ? Or is there a better alternative way ?

Any use of third-party libraries / modules would also be considered.

Upvotes: 0

Views: 150

Answers (3)

maurycy
maurycy

Reputation: 8465

The best way to do it is by service for couple of reasons.

  • If you use ng-view and routing the service is not reloading and your data is safe in service
  • It's easy injectable to controllers
  • Provides two-way data binding between controllers

working plunker with two-way data binding between controllers http://plnkr.co/edit/pt2xwlYqvY3r840tHJ92?p=preview

NOTE: if you don't have a dot in your model you are doing something wrong ;)

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52847

I think services are the way to go. Not only are they injectable but they are also Singletons - meaning wherever they are injected, the same instance is shared.

Example of a service which uses the $http service to make an asynchronous call to retrieve data:

app.factory('customerService', function($http)  {
   var customers = [];
   $http({ url: 'api/customers/all', method:'GET'}).success(function(data) {
       angular.copy(data, customers);
   });
   return {
      customers: customers
   };
});

In your controller or directive, you can then inject the service and bind customers to your scope:

app.controller('ctrl', function($scope, customerService) {
     $scope.customers = customerService.customers;
});

Upvotes: 1

Johnathan Hair
Johnathan Hair

Reputation: 151

I believe services are the best way for this.

I have used scope inheritance to place some methods that most of my app would need at once such as a routing method I attached these to the .run () method of my main module/app.

You could separate your models into separate modules if you needed to structure your app that way.

Upvotes: 0

Related Questions