Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

What is the best way to pass a Laravel route variable into an AngularJS controller or service?

For example I have a route of domain.com/contacts/87 where 87 is the contact's ID, this route shows the view/edit frontend for the Contact model with ID of 87. I want Angular to somehow get the ID of 87 to make a call to the RestfulAPI to retrieve a JSON representation of the Laravel Contact model, it will also be used for update and delete requests.

Partial from my AngularJS Contact service:

show: function (id) {
                var url = '/api/contacts/';
                return $http({
                    url: url+id,
                    method: "GET"                        
                });
            },
share|improve this question
    
You mean to get Angular read the variable from the URL? or how do you reach this route? – Mina Abadir Dec 7 '15 at 11:48

I think I have found the answer by passing in the ID using blade/php echo into the ng-init fore example:

<div class="container" ng-controller="contactController" ng-init="init({{$contact->id}})">

contactController partial:

$scope.init = function (contactID) {
            if (contactID) {
                $scope.contact.id = contactID;
                $scope.showContact();
            }
            ...
        };

Please let me know if this is a valid/safe way of doing this?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.