As a newcomer to Angular, I am exploring the best approach to accomplish a simple task.
My goal is to update the order of a Project model in a database using the Angular $resource service.
Here is my template structure:
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Date</th>
<th>Link</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody id="sortable" my-drag-list>
<tr ng-repeat="project in projects" ng-class="{warning: !project.publish}">
<td></td>
<td>{{project.title}}</td>
<td>{{project.date|date: 'MMMM yyyy'}}</td>
<td><a ng-href="{{project.link}}" target="blank">{{project.link}}</a></td>
<td><a ng-href="#/projects/{{project.id}}/"><span class="glyphicon glyphicon-edit"></span></a></td>
<td><a ng-click="deleteProject(project)"><span class="glyphicon glyphicon-trash"></span></a></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-success" ng-show="data.saveSort" my-update-sort-button>Save new sort</button>
The tr
elements in my tbody
are draggable. When I click on the button
(outside the scope of ng-repeat
), I want to update the database with new position values based on the DOM positions of each tr
element (lower position for upper tr
s).
Initially, I plan to create a my-update-sort-button
directive as follows:
var link = function(scope, el){
el.on('click', function(){
var els = el.parent().find('tr');
for(var i = 0, len = els.length; i<len; i++){
Projects.update({id: els.eq(i).data('projectId')}, {position: i});
}
});
};
However, I have doubts about the effectiveness of this solution. I am hesitant about adding a data-project-id
attribute to my tr
elements.
I appreciate any ideas or alternative solutions for this scenario!