Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does the business logic lies in angularjs?

Tags:

angularjs

Let's say on click of a button(in the view), the requirement is: to fetch the data from the server. I am confused whether or not the business logic to

i) fetch the data and

ii) validation of it should be done inside the controller or inside the factory(or service)

Should it be placed in the factory or in the controller? Please help!!

like image 608
ashok_khuman Avatar asked Jul 11 '14 09:07

ashok_khuman


People also ask

Where do we write business logic in Angular?

For anything but prototypes and simple or shortlived applications, anything but the simplest business logic should be extracted to class-based services or other dependencies. At the very least, components should be divided into presentational components and container components or a similar pattern.

What is Angular business logic?

Introduction. Kinvey Business Logic is a node. js code execution runtime that allows you to customize the behavior of requests to your backend by providing a means to implement server-side business logic.

What is workflow in AngularJS?

Extending an AngularJS Workflow¶ A workflow extends the extensibleService . This means that all workflows inherit properties and methods provided by the extensibleService . Extending a workflow allows you to add your own steps, remove existing steps, and inject custom data handling logic.

In which directory is AngularJS most important files stored?

top-level “app” folder : all angular files should be placed within a folder that could be named as “app”. “app” is the top-level folder. app/components folder: one or more components can be placed within “app/components” folder.


1 Answers

The purpose of controllers is binding data to your view. They should not contain any logic and merely communicate with your services.

homeModule.controller('homeCtrl',function($scope,Categories){
  $scope.categories = Categories.items;
});

Add a function to your service that fetches the data and stores it on itself:

fetchAll: function(){

  var defer = $q.defer();
  var self = this;

  $http.get(URL})
    .then(function(res){
        self.data = res.data;
        defer.resolve();
    });

  return defer.promise;
},

(Note that this is just one possible way to do things. Nothing prevents you from returning the data instead of storing it on the service. Do as you need.)

If possible, you should consider fetching your data before your view gets initialized. By doing so, you can ensure that necessary data is available as soon as the user get's the page.

See $http request before AngularJS app initialises?

Further reading

https://docs.angularjs.org/guide/services (Read the complete developer guide)

http://toddmotto.com/rethinking-angular-js-controllers/

Also I recommend the official Tutorial

like image 61
Wottensprels Avatar answered Oct 19 '22 02:10

Wottensprels