Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use AngularJS to retrieve nested resource in Rails

I have been working on implementing AngularJS into my Rails app based on the Railscast as a starting point. My question is similiar to this question: Angular JS ngResource with nested resources, however I have not found a solution to my problem.

Currently I have a nested resource which I am displaying on the view of the parent resource, via a partial. I need to supply the project_id in the query in order to retrieve the tasks, so I have:

app.factory "Task", ["$resource", ($resource) ->
  $resource("/projects/:project_id/tasks/:id", {project_id: "@project_id", id: "@id"}, {update: {method: "PUT"}})
]

@TaskCtrl = ["$scope", "Task", ($scope, Task) ->
  $scope.tasks = Task.query({project_id: "@project_id", id: "@id"})

My question is, how do I set '@project_id' in the view so that on the last line in my example the value is accessible in the controller? I tried using ng-init:

<div ng-controller="TaskCtrl" ng-init="project_id = <%= @project.id %>">

However once in my TaskCtrl controller 'project_id' is blank, and '$scope.project_id' does not work either. Any help is appreciated.

like image 203
Drew Avatar asked Jun 05 '13 12:06

Drew


1 Answers

ng-init runs before template execution, not before controller init. If only the template is aware of the project_id, create a shared service (it can be a simple value factory) which holds the project id and inject it to your controller. You can fill that service from another controller initialised before TaskController

<div ng-controller="ProjectIDController">
    <span ng-init="project_id = <%= @project.id %>"></span>
</div>

<div ng-controller="TaskCtrl">
    ...
</div>

function ProjectIDController( $scope, sharedService ) {
    $scope.$watch('project_id', function (UID) {
        sharedService.setProjectID($scope.project_id);
    });
}

function TaskCtrl ($scope, Task, sharedService) {
    $scope.tasks = Task.query({project_id: sharedService.getProjectId()... 
}

sorry for not coffee...

like image 53
Oliver Avatar answered Nov 10 '22 00:11

Oliver