I have a typical projects/tasks/subtasks CRUD app, and one can navigate from a top level project listing all the way down to a subtask.
All resources are routed, e.g.
/projects to get all projects,
/projects/:id to get a specific project,
/projects/:id/tasks to get all tasks for a specific project, and so on.
I render tasks like so:
<ul>
<li ng-repeat="task in tasks">
<a href="/tasks/{{task.id}}">
{{task.name}}</a> ...
The controller responsible for the /tasks/:id route gets the data using the $routeParams from the backend API, but I was wondering how to load the task from the information I already have in the scope I link from, e.g. something like:
<ul>
<li ng-repeat="task in tasks">
<a href="/tasks/{{task.id}}" ng-click="useThisTaskInstead(task)">
<!-- ^^^^^^^^^^^^^^^^^^ -->
<!-- set this in the
target scope. -->
{{task.name}}</a> ...
I want the target controller to only contact the backend API if the task isn't in scope.
The URL in the address bar should also still show http://example.org/tasks/5, for example.
UPDATE
Something I tried which I'm unsure about:
I have a top-level ApplicationController in which I define:
$scope.cacheTask: function (task) {
$scope.task = task;
};
...and then the link becomes:
<a href="/tasks/{{task.id}}" ng-click="cacheTask(task)">
...and in my TaskController:
if (typeof $scope.task !== 'undefined' && $scope.task.id == $routeParams.id) {
// nothing to do -- task already set in scope.
console.log("task already in scope");
} else {
console.log("fetching task");
// load task
$q.when(taskService.get($routeParams.id).$promise).then(function(task) {
console.log("task fetched from backend", task);
// set the task in scope
$scope.task = task;
});
}