Vikram Singh Jadon
Vikram Singh Jadon

Reputation: 1047

Angular JS - Cannot identify the suitable place to put a piece of code that will be used by different pages

I am making a page that is extracting some information from the server and showing it on the interface. I am using angular js for this. So I have made a controller that has $http.get() method which gets data from the server and then the data binding is used to bind data to the html page. I am using this controller...

    mission_vision_mod.controller('mission_visionCtrl', ['$scope','$http', function($scope, $http) {
        $scope.visiontext = "Here is the content of vision";
        $scope.bkclr = ['bk-clr-one','bk-clr-two','bk-clr-three','bk-clr-four'];
        $scope.progressbar = ['progress-bar-warning','progress-bar-danger','progress-bar-success','progress-bar-primary'];
        $scope.missioncount = ['col-md-0','col-md-12','col-md-6','col-md-4','col-md-3','col-md-2.5','col-md-2'];

        $http.get('m_id.json').success(function(data){
            $scope.missions = data;
            $scope.len = data.length;
        });
}]);

Now i want to make a page that allows the users to edit this info, this page also requires the same above code (code inside the controller). I also have to make a different controller for the new page to send whatever data that has been edited to server. How do i use the above code for both the pages while i have to make a new controller for the second one for editing purpose. I want to use the same code for both the controllers.

Upvotes: 0

Views: 54

Answers (2)

Shushanth Pallegar
Shushanth Pallegar

Reputation: 2862

Service/factory/value are meant for this , please refer the below example hope you get a better idea .

 var app = angular.module('myApp',[]);

 //controller 

  app.controller('myCtrl',myCtrl);

  //inject dependencies

  myCtrl.$inject = ["$scope","httpService"];

   function myCtrl($scope,httpFactory){
        $scope.data = httpFactory.getData;

    }


//factory : http factory

      app.factory('httpFactory',httpFactory);

      //inject dependencies

        httpFactory.$inject = ["$http"];

       function httpFactory($http){
             var datas = [];
            return {

               getData:function(){

                      $http.get('url').success(function(data){
                           datas.push(data);
                          }).
                        error(function(){
                              console.log('error');
                        });
                     return datas
                  }

            }

          }

Upvotes: 1

Cliff
Cliff

Reputation: 162

I would suggest moving that code to a Service, then inject and use that service in each of the controllers where you need this functionality.

Services are often the best place to add code that is shared between multiple controllers or if you need a mechanism to pass data betweeen controllers.

Hope this helps!

Upvotes: 2

Related Questions