0

Hi I am a newbie and learning angular.js. I want to get data from this url which is actually an API (http://ba.dev/businesses/businesspage/36) but i dont know how can i Write this thing in my controller.js file. Given is my code please explain me how can I get the data from the business having id=36.

var reControllers = angular.module('reControllers',[]);
reControllers.controller('RecentController', ['$scope','$http' ,function($scope,$http){
    $http.get('http://ba.dev/businesses/businesses').success(function(data){
        $scope.business = data;
     }); 
}]);

reControllers.controller('PageController', ['$scope','$http', '$routeParams' ,function($scope,$http,$routeParams){
    $http.get('http://ba.dev/businesses/businesspage').success(function(data){
        $scope.student = data;
        $scope.whichItem = $routeParams.itemId; 
    }); 
}]);

Here is my app.js file

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

myApp.config(['$routeProvider', function($routeProvider){   
    $routeProvider.                      
        when('/main',{               
        templateUrl : 'partials/main.html',
        controller : 'RecentController'
    }).
    when('/page/:itemId',{
        templateUrl : 'partials/page.html',
        controller  : 'PageController'
    }).
    otherwise({                   
        redirectTo: '/main'   
    });
}]);     

2 Answers 2

1

You can get the id from URL using $routeParams

$http.get('http://ba.dev/businesses/businesspage/'+ $routeParams.itemId)

Thereafter add server side logic, get passed itemId from URL, perform needful operation for getting data from DB and return it back.

Sign up to request clarification or add additional context in comments.

Comments

0

You should use then instead of success, because it is deprecated. So, your code should be: `

$http.get('http://ba.dev/businesses/businesses').then(function(data){
 $scope.business = data;
 }); }]);.....

From AngularJS documentation:

    // Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

More info about route params: AngularJS $routeParams

1 Comment

Even if people shouldn't use the success and error (your tip is correct, of course) it doesn't answer the question. In fact, it should be a complement of a suppose answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.